KrishnaTeja
KrishnaTeja

Reputation: 117

How separate keys and values in this JSON object, using Java?

I have JSON object like

{
 "projector":"no",
 "video_conference":"no",
 "polycom":"no",
 "lcd":"no",
 "digital_phone":"no",
 "speaker_phone":"no"
}

How do I store the keys in one array and the values in a separate array?

Upvotes: 1

Views: 4532

Answers (3)

MayurB
MayurB

Reputation: 3649

Try GSON for converting your java object to json and vice versa.

Refer this link

http://code.google.com/p/google-gson/

Upvotes: 3

Cody A. Ray
Cody A. Ray

Reputation: 6027

I like Jackson from http://codehaus.org/ for JSON parsing.

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()]);

Upvotes: 1

Kumar Shorav
Kumar Shorav

Reputation: 531

You may try this.

 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;

        }

Upvotes: 1

Related Questions