如何使用Java在此JSON对象中分隔键和值?

时间:2013-02-12 04:55:10

标签: java json

我有像

这样的JSON对象
{
 "projector":"no",
 "video_conference":"no",
 "polycom":"no",
 "lcd":"no",
 "digital_phone":"no",
 "speaker_phone":"no"
}

如何将键存储在一个数组中,将值存储在单独的数组中?

4 个答案:

答案 0 :(得分:3)

尝试GSON将您的java对象转换为json,反之亦然。

参考此链接

<强> http://code.google.com/p/google-gson/

答案 1 :(得分:1)

我喜欢http://codehaus.org/的杰克逊进行JSON解析。

String text = "{ \"projector\":\"no\", \"video_conference\":\"no\", \"polycom\":\"no\", \"lcd\":\"no\", \"digital_phone\":\"no\", \"speaker_phone\":\"no\" }";

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(text, Map.class);
Set<String> k = map.keySet();
Collection<Object> v = map.values();

String[] keys = k.toArray(new String[k.size()]);
String[] values = v.toArray(new String[v.size()]);

答案 2 :(得分:1)

你可以试试这个。

 String s = " { "projector":"no", "video_conference":"no", "polycom":"no", "lcd":"no", "digital_phone":"no", "speaker_phone":"no" }";

        JSONObject jObject  = new JSONObject(s);
        JSONObject  menu = jObject.getJSONObject("projector");


        Iterator iter = menu.keys();
    String[] keyArr = new String();
    String[] valArr = new String();
    int count = 0;
        while(iter.hasNext()){
                 keyArr[count] = (String)iter.next();

             valArr[count] = menu.getString(key);
           count +=1;

        }

答案 3 :(得分:0)

此问题已经回答请查看以下链接 How to store values of JSON in ARRAY/ String