如何将json字符串反序列化为对象 [英] How to deserialize json string into object

查看:119
本文介绍了如何将json字符串反序列化为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  {
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,
名称:地点,
accessibleToUser:false,
defaultLocation:false,
timezoneId:Asia / Calcutta,
children {
type:locallocationid,
id:1
}]
},
allAllowedChildren:[{
type :locallocationid,
id:1
}]

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

使用的类是

  public class Tree {

@SerializedName( allAllowedChildren)
私人列表< Id> allAllowedChildren;

@SerializedName(LocalLocationId)
私人地图< String,LocalLocationId> localLocationId;

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

@SerializedName(name)
私人字符串名称;

@SerializedName(accessibleToUser)
private boolean accessibleToUser;

@SerializedName(defaultLocation)
private boolean defaultLocation;

@SerializedName(timezoneId)
private String timezoneId;

@SerializedName(id)
私人ID号;

@SerializedName(parentId)
private Id parentId;

@SerializedName(children)
私人列表< Id>儿童;

public String getType(){
返回类型;
}
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;
}
公开列表< Id> getChildren(){
返回儿童;
}
}

公共类ID {
私有字符串类型;
私人整数ID;

public String getType(){
返回类型;
}
public Integer getId(){
return id;
}
}

公开列表< Id> getAllAllowedChildren(){
return allAllowedChildren;
}
public Map< String,LocalLocationId> getLocalLocationId(){
return localLocationId;
}
}


解决方案

@基达



我假设您控制着如何创建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:{
键入:locallocationid,
id:0
},
par entId:null,
name:Locations,
accessibleToUser:false,
defaultLocation:false,
timezoneId:Asia / Calcutta ,
children:[{
type:locallocationid,
id:1
}]
}
]
$ ballAllowedChildren:[{
type:locallocationid,
id:1
}]
}

请评论我对输入字符串的假设是否有误。



<编辑1:
由于输入无法修改,因此可以考虑编写自定义的Deserializer。
以下是注册自定义反序列化类的方法


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

以下是TreeDeserializer

  public class TreeDeserializer实现JsonDeserializer< Tree> {

公共树反序列化(JsonElement json,类型typeOfT,
JsonDeserializationContext上下文)抛出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将其添加回Tree out对象
} else {
// LocalLocationId
System.out.println(e.getKey());
System.out.println(context.deserialize(e.getValue(),Tree.LocalLocationId.class));

// TODO加回到Tree out对象
}
}
}
返回;
}

}

以下是控制台的输出

  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类中。希望这可以帮助。无法提供完整的实施,但我认为这将是一个部分解决方案


{
   "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
   }]
}

How to deserialize above string into java object.

Class im using is

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

I'll assume you are in control of how the JSON input string is created. I think the JSON string is not formatted correctly for default GSON deserialization of Map types.

I have modified the input string for your consideration and this results in a non null 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
   }]
}

Please comment if my assumption about the input string is incorrect.

EDIT 1: Since input cannot be modified, consider writing custom Deserializer. Below is the way to register custom deserialisation class

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

Below is the 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;
    }

}

Here is the console output from the 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

I have left TODOs in the deserialiser where you'll need to write custom code to inject the values from deserialisation into the Tree class just created. Hope this helps. Can't provide full implementation, but I think this would be a partial solution

这篇关于如何将json字符串反序列化为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆