我正在使用Gson将JSON转换为Java对象。我在json中有一个字段,我们明智的服务人员编码为数组或对象,具体取决于数据库中有多少项返回。问题是如何模拟Java对象传递到Gson转换器,以便我可以处理这两种类型?
json = new Gson().fromJson(reader, Order.class);
Java Classes只能正确解析JSON数组
public class Order {
private Detail detail
}
public class Detail {
public String id;
public List<Type> types;
//// getters and setters
}
public class Type {
public String typeId;
public String typeName
//// getters and setters
}
JSON数据数组
{
"detail":{
"id":"1234565",
"types":{
"type":[
{"typeId":"1246565","typeName":"MyName1"},
{"typeId":"1444445","typeName":"MyName2"}
]
}
}
}
JSON数据对象
{
"detail":{
"id":"1234565",
"types":{
"type":{"typeId":"1246565","typeName":"MyName1"}
}
}
}
答案 0 :(得分:1)
我想通过使用通用对象来解决这个问题。所以现在我仍然可以使用GSON进行调用,而且只有当我需要重构对象时才需要进行那么多的手动解析,而且只需要那个特定的对象。
json = new Gson().fromJson(reader, Order.class);
主要对象
public class Order {
private Detail detail
}
详情课程
public class Detail {
public String id;
public Types types;
//// getters and setters
public Types getTypes() {
return types;
}
public void setTypes(Types types) {
this.types = types;
}
}
包含一个名为type的通用Object的Types类,因此它可以存储List 或者是LinkedTreeMap,它是JSONObject被解析的方式。然后,您必须手动将其插入到新的Type对象中。
public class Types {
private Object type;
//// getters and setters
public Object getType() {
return type;
}
public void setType(Object type) {
this.type = type;
}
public List<Type> getListType() {
if (type instanceof List) {
return (List<Type>) type;
} else
return null;
}
public Type getObjectType() {
if (type instanceof Type) {
return (Type) type;
} else if (type instanceof Map) {
Map<String, String> map = (Map<String, String>)type;
Type newType = new Type((String)map.get("typeId"), (String)map.get("typeName"));
return newType;
}
return null;
}
public class Type {
private String typeId;
private String typeName;
public Type() {}
public Type(String id, String name) {
this.typeId = id;
this.typeName = name;
}
//// getters and setters
public String getTypeId() {
return typeId;
}
public void setTypeId(String typeId) {
this.typeId = typeId;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
答案 1 :(得分:-1)
嗟!!
JsonArray typeArray;
JsonElement typeElement = types.get("type");
if (typeElement.isJsonObject()) {
typeArray = new JsonArray();
typeArray.add(typeElement);
}
else {
typeArray = (JsonArray)typeElement;
}
for (int i = 0; i < typeArray.size(); i++) {
JsonObject typeObject = (JsonObject)(typeArray.get(i));
typeObject.doSomethingWithThis();
}