仅使用字符串和值解析 JSON 对象 [英] Parse JSON object with string and value only

查看:32
本文介绍了仅使用字符串和值解析 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用最小值进行解析以在 Android 中映射时遇到问题.

I have problem when trying to parse with minimum value to map in Android.

有一些带有更多信息的示例 JSON 格式,例如:

There some sample JSON format with more information ex:

[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]

这个最常用且易于使用的示例只需使用 getString("id")getValue("name").

This that example most common to use and easy to use just use getString("id") or getValue("name").

但是我如何使用这种 JSON 格式解析映射,只使用字符串和值最小格式,使用循环将其映射到 java 映射集合.并且因为字符串 json 总是与另一个不同.例如:

But how do I parse to map using this JSON format with just only string and value minimum format to java map collection using looping. And because the string json will always different one with another. ex:

{"1":"sql", "2":"android", "3":"mvc"}

谢谢

推荐答案

您需要获取所有键的列表,遍历它们并将它们添加到您的地图中,如下例所示:

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{"1":"sql", "2":"android", "3":"mvc"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

这篇关于仅使用字符串和值解析 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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