我有以下JSON:
{
"LightObjectSet": {
"Objects": {
"Org": {
"State": "Unchanged",
"Guid": "00000000-0000-0000-0000-000000000000",
"Id": "39",
"Name": "Test org",
"ShortName": "Test"
}
}
}
}
我可以使用Gson反序列化Org
对象(不是所有结构)吗?
答案 0 :(得分:0)
试试这个。请注意,反序列化的Org
类不遵循Java命名约定来匹配JSON。如果您想关注它们,则需要使用@SerializedName
public class Q13363304 {
class Org {
String State;
String Guid;
int Id;
String Name;
String ShortName;
@Override
public String toString() {
return "Org [State=" + State + ", Guid=" + Guid + ", Id=" + Id
+ ", Name=" + Name + ", ShortName=" + ShortName + "]";
}
}
/**
* @param args
*/
public static void main(String[] args) {
String json = "{ \"LightObjectSet\": { \"Objects\": { \"Org\": { \"State\":\"Unchanged\", \"Guid\":\"00000000-0000-0000-0000-000000000000\", \"Id\":\"39\", \"Name\":\"Test org\", \"ShortName\":\"Test\" } } } }";
JsonObject root = new JsonParser().parse(json).getAsJsonObject();
JsonObject lightObjectSet = root.get("LightObjectSet").getAsJsonObject();
JsonObject objects = lightObjectSet.get("Objects").getAsJsonObject();
JsonElement org = objects.get("Org");
Gson g = new Gson();
Org o = g.fromJson(org, Org.class);
System.out.print(o);
}
}