简体   繁体   English

json(gson)解析会在解析时更改数据类型

[英]json (gson) parse changes the type of data when parsing

I have a json string which looks something like this : 我有一个看起来像这样的json字符串:

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

When I use gson parser to convert that to a Map<String,String> map . 当我使用gson解析器将其转换为Map<String,String> map The gson converts the type to Map<String,ArrayList> . gson将类型转换为Map<String,ArrayList> And when I try to print the class name using System.out.println(map.get("employees").getClass().toString()) . 当我尝试使用System.out.println(map.get("employees").getClass().toString())打印类名时。 But this throws an exception - java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String . 但这会引发异常java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.String

my code looks something like this 我的代码看起来像这样

String npv = json_string_provided_above;
Map<String,String> mp = new HashMap<String, String>();
mp = new Gson().fromJson(npv,mp.getClass());
System.out.println(mp.get("employees").getClass().toString());

The json is given as input by user in string format(and it will always be a valid json string). json是由用户以字符串格式输入的(并且它将始终是有效的json字符串)。 And one thing is sure that I can't assume anything about the type of data. 一件事可以肯定,我不能对数据类型承担任何责任。 Because it will be provided by user. 因为它将由用户提供。

So now actually I want that even If the user inputs something like arrays of string or arrays of objects. 因此,即使用户输入了字符串数组或对象数组之类的东西,现在我实际上还是希望这样做。 It should not convert the them to List, 它不应该将它们转换为List,

Is there is a way I can hard code the type and keep them in Map<String,String> . 有没有一种方法可以对类型进行硬编码并将它们保留在Map<String,String> so in the above example when I do map.get("employees") it should give me the [{"firstName":"John", "lastName":"Doe"},{"firstName":"Anna", "lastName":"Smith"},{"firstName":"Peter", "lastName":"Jones"}] as string not list. 因此在上面的示例中,当我执行map.get("employees")它应该给我[{"firstName":"John", "lastName":"Doe"},{"firstName":"Anna", "lastName":"Smith"},{"firstName":"Peter", "lastName":"Jones"}]作为字符串未列出。 I am not sure how to do this. 我不确定该怎么做。

Thank you for your help, 谢谢您的帮助,

Jon is right, just use Map<String, Object> 乔恩是正确的,只需使用Map<String, Object>

String npv = json_string_provided_above;
Map<String,Object> mp = new HashMap<String, Object>();
mp = new Gson().fromJson(npv, mp.getClass());
System.out.println(mp.get("employees").toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM