我从我的API中获得了一个JSON字符串,如下所示:
I've got an JSON string from my API, looks like this:
[ { "id": "abc", "data": { "Name": "Peter", "Date": "2017/12/01" } }, { "id": "def", "data": { "Name": "Tina", "Date": "2017/12/20" } }, { "id": "ghi", "data": { "Name": "Amy", "Date": "2017/12/16" } } ]然后,我使用(java):
Then, I use (java):
Gson gson = new Gson(); Type resultType = new TypeToken<List<Map<String, Object>>>() { }.getType(); List<Map<String, Object>> result = gson.fromJson(info, resultType);如果我调用result.get(0).toString());然后它返回:
if I call result.get(0).toString()); then it returned:
{id=abc, data={Name=Peter, Date=2017/12/01}}如果我调用result.get(0).get("id").toString();然后它返回
if I call result.get(0).get("id").toString(); then it returned
abc
现在,当我调用result.get(0).get("data").toString();时,我想获取"data"的数据.然后它返回了
Now I want to get the data of "data", when I call result.get(0).get("data").toString(); then it returned
{Name=Peter, Date=2017/12/01}最后,我想获取名称"信息,但是当我尝试将此字符串转换为Map时,这会导致一些问题,代码如下:
Finally I want to get the "Name" info, but when I tried to convert this string to Map, it cause some problem, the code is like this:
Type type = new TypeToken<Map<String, Object>>(){}.getType(); Map<String, Object> myMap = gson.fromJson(str, type);这不起作用.我发现该字符串可能不是JSON的通用类型,它类似于"Name = Peter,Date = 2017/12/01",但它需要"Name":"Peter","Date":"2017/12"/01,对吗?那是问题吗?如何获取姓名的数据?谁能帮我吗?
This doesn't work. I found that maybe the string is not a general type of JSON, it is like "Name=Peter, Date=2017/12/01", but it needs "Name": "Peter", "Date": "2017/12/01" , right? Is that the problem? How can I get the data of Name? Can anyone help me?
已更新:我发现如果"Name" =",则无法将其获取为字符串类型,则无法使用"data.get(" Name);".但是我仍然需要它.任何人都可以修复它吗?谢谢.
Updated: I found that if "Name" = "", then I couldn't get it as string type, I cannot use "data.get("Name");". But I still need it. Anyone can fix it? Thanks.
推荐答案首先,您的JSON格式不正确,日期后不应使用逗号.并回答您的问题,根本不要使用地图.
First of all, your JSON is malformed, it shouldn't have a comma after date. and to answer your question, don't use map at all.
如果您确实想在不创建模型和其他类的情况下执行此操作,请按照以下方式进行操作:
If you really want to do it without creating a model and additional classes, do it this way:
Gson gson = new Gson(); Type resultType = new TypeToken<List<JsonObject>>() {}.getType(); List<JsonObject> result = gson.fromJson(info, resultType); System.out.println(result.get(0).get("data").toString()); JsonObject data = result.get(0).get("data").getAsJsonObject(); System.out.println(data.get("Name"));更多推荐
如何从JSON列表的JSON列表中获取数据
发布评论