如何将JSON字符串反序列化为对象

3
{
   "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;
    }
}

4
你遇到了哪些错误? - dotvav
使用您当前正在使用的类,将上述字符串反序列化为Java对象是不可能的。 - Ryan Fung
@RyanFung 能否详细说明一下?我猜测楼主不知道为什么会出现这种情况。 - Andy Turner
@KedarJavalkar 对不起,我的回复太快了。您的类对象将不会被存储或难以存储。"树形"结构更加适合。 - Ryan Fung
希望这个链接能解决你的问题:http://programmerbruce.blogspot.com/2011/06/gson-v-jackson.html#TOC-Nested-Classes-including-Inner-Clas - Noor Nawaz
显示剩余2条评论
4个回答

1

@Kedar

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

我已经修改了输入字符串供您参考,这将导致非空的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,您需要编写自定义代码将反序列化的值注入到刚创建的Tree类中。希望这可以帮助您。无法提供完整实现,但我认为这将是部分解决方案。


JSON字符串是从第三方API接收的,其格式与我所提到的完全相同。 - Kedar Javalkar
好的,那么我可以看到唯一的选择就是编写自己的代码来执行反序列化的部分。 - vvs
我之前也做过类似把字符串解析成“树”类的操作,我会尝试一下你的方法的。祝你好运! - Kedar Javalkar

0

使用JSONParser,它是更快的解析器。

以下是示例。如果您搜索谷歌,可能会找到更好的示例。希望这可以帮助您。

JSONParser parser=new JSONParser();
System.out.println("=======decode=======");
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";  
Object obj=parser.parse(s);  
JSONArray array=(JSONArray)obj;  
System.out.println("======the 2nd element of array======");  
System.out.println(array.get(1));  
System.out.println();                  
JSONObject obj2=(JSONObject)array.get(1);  
System.out.println("======field \"1\"==========");  
System.out.println(obj2.get("1"));                      
s="{}";  
obj=parser.parse(s);  
System.out.println(obj);                  
s="[5,]";  
obj=parser.parse(s);  
System.out.println(obj);                  
s="[5,,2]";  
obj=parser.parse(s);  
System.out.println(obj);

0

您可以使用Gson..

String json = "Your json string "
Tree treeObj= new Gson().fromJson(json, Tree .class);

运行上述代码会导致localLocationId映射结果为null - Kedar Javalkar
我看到你需要修改你的JSON字符串,它的格式不正确。 - Manisha Srivastava

-1

你可以使用Jackson的ObjectMapper-

Tree deserializedTree = new ObjectMapper().readValue(jsonStringOfTree, Tree.class);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接