0

I have some function where I receive such JSON:

String sorting ->>  {"state":"desc"}
String filter  ->> {"clientID":"XML"}

All value within are always different. How can I get Key and Value for such JSON?

Lets say :

KEYsorting =state , Valuesorting  = desc 
KEYfilter =clientID, Valuefilter  = XML

I have searched a lot - including this website - but couldn't dealt with it. I guess it is not very difficult I I wasn't able to do that. Please help

Kruti Patel
  • 1,422
  • 2
  • 23
  • 36
Irakli
  • 973
  • 3
  • 19
  • 45
  • 1
    You may have a look at GSON library : https://sites.google.com/site/gson/gson-user-guide – Nikolay Tomitov Feb 11 '16 at 07:50
  • Possible duplication of http://stackoverflow.com/questions/5245840/how-to-convert-string-to-jsonobject-in-java In any case the solution offered there by using JsonObject looks applicable in your case as well – Mark Bramnik Feb 11 '16 at 07:59
  • @MarkBramnik he want to convert it into JSON - I want to convert them into variables. – Irakli Feb 11 '16 at 08:01
  • @NikolayTomitov GSON library needs certain class structure to parse such string. I don't have structure. name of all columns will always change – Irakli Feb 11 '16 at 08:03
  • Yes, but you state that variables are always different, so you can't really create new values in runtime. So you need a level of abstraction - a map that has a key = variable name and value = the actual value. JsonObject does just that. I really suggest you to play with it for a couple of minutes and you'll see that it suits your needs – Mark Bramnik Feb 11 '16 at 08:04
  • @MarkBramnik you was right as well. thanks – Irakli Feb 11 '16 at 08:37

1 Answers1

4

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 sorting = "{\"state\":\"desc\"}";
JSONObject  filter = new JSONObject(sorting);

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

you can try above example.

Kruti Patel
  • 1,422
  • 2
  • 23
  • 36