2

我有以下 JSON:

{
   "LightObjectSet": {
      "Objects": {
         "Org": {
            "State": "Unchanged",
            "Guid": "00000000-0000-0000-0000-000000000000",
            "Id": "39",
            "Name": "Test org",
            "ShortName": "Test"
         }
      }
   }
}

我可以Org使用 Gson 仅反序列化对象(不是所有结构)吗?

4

1 回答 1

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);

    }

}
于 2013-11-12T06:30:39.910 回答