gpt4 book ai didi

java - 从 Java 对象到 JSON 对象的自定义转换

转载 作者:行者123 更新时间:2023-12-04 05:26:22 26 4
gpt4 key购买 nike

我有以下代码

Gson gson = new Gson();
String json = gson.toJson(criteria.list()); // list is passed by Hibernate

结果将是这样的:
{creationTime:0, enabled:true, id:1, loginDuration:0, online:false, userName:someone}

我想在 JSON 响应中添加新属性(DT_RowId 与 id 具有相同的值)。最终结果应该是这样的:
{creationTime:0, enabled:true, id:1, loginDuration:0, online:false, userName:someone, DT_RowId=1}

更新

为了解决这个问题,我在实体上创建了一个带有 @Transient 注释的字段。
    ...
@Transient
private long DT_RowId;

public void setId(long id) {
this.id = id;
this.DT_RowId=id;
}
...

但是从未调用过 setId 函数。有人可以启发我吗?

最佳答案

GSON 不会调用你的 getter 和 setter。它通过反射直接访问成员变量。要完成您要执行的操作,您需要使用 GSON 自定义序列化器/解串器。 The GSON docs on custom serializers/deserializers提供一些关于如何执行此操作的示例。

这是一个通过 JUnit 测试的工作示例,演示了如何执行此操作:

实体.java

public class Entity {
protected long creationTime;
protected boolean enabled;
protected long id;
protected long loginDuration;
protected boolean online;
protected String userName;
protected long DT_RowId;
}

EntityJsonSerializer.java
import java.lang.reflect.Type;
import com.google.gson.*;

public class EntityJsonSerializer implements JsonSerializer<Entity> {
@Override
public JsonElement serialize(Entity entity, Type typeOfSrc, JsonSerializationContext context) {
entity.DT_RowId = entity.id;
Gson gson = new Gson();
return gson.toJsonTree(entity);
}
}

JSONTest.java
import static org.junit.Assert.*;
import org.junit.Test;
import com.google.gson.*;

public class JSONTest {
@Test
public final void testSerializeWithDTRowId() {
Entity entity = new Entity();
entity.creationTime = 0;
entity.enabled = true;
entity.id = 1;
entity.loginDuration = 0;
entity.online = false;
entity.userName = "someone";

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Entity.class, new EntityJsonSerializer());
Gson gson = builder.create();
String json = gson.toJson(entity);
String expectedJson = "{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"userName\":\"someone\",\"DT_RowId\":1}";
assertEquals(expectedJson, json);
}
}

关于java - 从 Java 对象到 JSON 对象的自定义转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13175019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com