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

@Kedar

我假设您控制着JSON输入字符串的创建方式.

我认为JSON字符串的格式不正确,无法对地图类型进行默认的GSON反序列化.

我已修改输入字符串供您考虑,这将导致非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

}]

}

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

编辑1:

由于无法修改输入,请考虑编写自定义解串器.

以下是注册自定义反序列化类的方法

GsonBuilder gsonb = new GsonBuilder();

gsonb.registerTypeAdapter(Tree.class, new TreeDeserializer());

Gson gson = gsonb.create();

下面是TreeDeserializer

public class TreeDeserializer implements JsonDeserializer {

public Tree deserialize(JsonElement json, Type typeOfT,

JsonDeserializationContext context) throws JsonParseException {

Tree out = new Tree();

if (json != null) {

JsonObject obj = json.getAsJsonObject();

Set> entries = obj.entrySet();

for (Map.Entry 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类中.希望这可以帮助.无法提供完整的实现,但我认为这将是部分解决方案

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值