java - 如何将json字符串反序列化为对象

标签 java gson

{
   "LocalLocationId [id=1]":{
      "type":"folderlocation",
      "id":{
         "type":"locallocationid",
         "id":1
      },
      "parentId":{
         "type":"locallocationid",
         "id":0
      },
      "name":"Test",
      "accessibleToUser":true,
      "defaultLocation":false,
      "timezoneId":"Asia/Calcutta",
      "children":[]
   },
   "LocalLocationId [id=0]":{
      "type":"folderlocation",
      "id":{
         "type":"locallocationid",
         "id":0
      },
      "parentId":null,
      "name":"Locations",
      "accessibleToUser":false,
      "defaultLocation":false,
      "timezoneId":"Asia/Calcutta",
      "children":[{
         "type":"locallocationid",
         "id":1
      }]
   },
   "allAllowedChildren":[{
      "type":"locallocationid",
      "id":1
   }]
}

如何将上面的字符串反序列化为java对象。

我使用的类是

public class Tree {

    @SerializedName("allAllowedChildren")
    private List<Id> allAllowedChildren;

    @SerializedName("LocalLocationId")
    private Map<String, LocalLocationId> localLocationId;

    public class LocalLocationId {
        @SerializedName("type")
        private String type;

        @SerializedName("name")
        private String name;

        @SerializedName("accessibleToUser")
        private boolean accessibleToUser;

        @SerializedName("defaultLocation")
        private boolean defaultLocation;

        @SerializedName("timezoneId")
        private String timezoneId;

        @SerializedName("id")
        private Id id;

        @SerializedName("parentId")
        private Id parentId;

        @SerializedName("children")
        private List<Id> children;

        public String getType() {
            return type;
        }
        public String getName() {
            return name;
        }
        public boolean isAccessibleToUser() {
            return accessibleToUser;
        }
        public boolean isDefaultLocation() {
            return defaultLocation;
        }
        public String getTimezoneId() {
            return timezoneId;
        }
        public Id getId() {
            return id;
        }
        public Id getParentId() {
            return parentId;
        }
        public List<Id> getChildren() {
            return children;
        }
    }

    public class Id {
        private String type;
        private Integer id;

        public String getType() {
            return type;
        }
        public Integer getId() {
            return id;
        }
    }

    public List<Id> getAllAllowedChildren() {
        return allAllowedChildren;
    }
    public Map<String, LocalLocationId> getLocalLocationId() {
        return localLocationId;
    }
}

最佳答案

@Kedar

我假设您可以控制 JSON 输入字符串的创建方式。 我认为对于 Map 类型的默认 GSON 反序列化,JSON 字符串的格式不正确。

我已经修改了输入字符串供您考虑,这会导致 LocalLocationId 非空

{
   "LocalLocationId":[
   [
     "1",
       {
          "type":"folderlocation",
          "id":{
             "type":"locallocationid",
             "id":1
          },
          "parentId":{
             "type":"locallocationid",
             "id":0
          },
          "name":"Test",
          "accessibleToUser":true,
          "defaultLocation":false,
          "timezoneId":"Asia/Calcutta",
          "children":[]
       }
   ],
   [
     "2",
       {
          "type":"folderlocation",
          "id":{
             "type":"locallocationid",
             "id":0
          },
          "parentId":null,
          "name":"Locations",
          "accessibleToUser":false,
          "defaultLocation":false,
          "timezoneId":"Asia/Calcutta",
          "children":[{
             "type":"locallocationid",
             "id":1
          }]
       }
   ]
   ],
   "allAllowedChildren":[{
      "type":"locallocationid",
      "id":1
   }]
}

如果我对输入字符串的假设不正确,请发表评论。

编辑1: 由于无法修改输入,请考虑编写自定义反序列化器。 下面是注册自定义反序列化类的方法

GsonBuilder gsonb = new GsonBuilder();
        gsonb.registerTypeAdapter(Tree.class, new TreeDeserializer());
        Gson gson = gsonb.create();

下面是 TreeDeserializer

public class TreeDeserializer implements JsonDeserializer<Tree> {

    public Tree deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
        Tree out = new Tree();

        if (json != null) {
            JsonObject obj  = json.getAsJsonObject();
            Set<Map.Entry<String,JsonElement>> entries = obj.entrySet();
            for (Map.Entry<String, JsonElement> e: entries) {
                if (e.getKey().equals("allAllowedChildren")) {
                    Type ft = List.class;
                    System.out.println(context.deserialize(e.getValue(), ft));
                    // TODO add this back into the Tree out object
                } else {
                    // LocalLocationId
                    System.out.println(e.getKey());
                    System.out.println(context.deserialize(e.getValue(), Tree.LocalLocationId.class));

                    // TODO add this back into the Tree out object
                }
            }
        } 
        return out;
    }

}

这是 Sysouts 的控制台输出。

LocalLocationId [id=1]
org.test.StackOverflowAnswers.Tree$LocalLocationId@464bee09
LocalLocationId [id=0]
org.test.StackOverflowAnswers.Tree$LocalLocationId@f6c48ac
[{type=locallocationid, id=1.0}]
org.test.StackOverflowAnswers.Tree@589838eb

我已将 TODO 留在反序列化器中,您需要编写自定义代码以将反序列化中的值注入(inject)到刚刚创建的 Tree 类中。希望这可以帮助。无法提供完整的实现,但我认为这将是部分解决方案

关于java - 如何将json字符串反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32860614/

相关文章:

java - C++:如何在独立的源文件上定义类,然后在主程序中使用它们?

java - 如何解决java中方法的通用输入参数

java - Gson:如何更改枚举的输出

java - 注释类型 SerializedName 未定义属性 "alternate"

java - 仅对某些 GSON 方法调用返回 JsonObject Null

java - 我的 Spring SecurityConfig 没有被获取

java - 在 Jenkins 中为 Java 11 指定 JAVA_HOME

java - 启动 webstart 而不下载...?

java - ProGuard:ClassCastException

json - 使用gson解析json时如何忽略重复的键?