Parse JSON with Unknown values - java

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

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.

Related

JSONObject not workign

I am building an app for android.
I fire and HTTP GET request and this request returns a JSONObject. I want to retrieve the value by key. But this is not working properly.
This is the JSONObject named obj that I receive:
{"id":1,"name":"math","description":"This is a math course."}
If I log Log.d("title", String.valueOf(obj.has("name"))); this will result into true.
This works for all keys in the JSONObject.
But if I want to receive the name and do this so:
Log.d("title", obj.getString("name"));
I will get an unhandled exception: org.json.JSONException.
Does anybody know how I can fix this problem?
Maybe you should try someting like this:
Log.d("title", obj.name);
var obj = $.parseJSON('{"id":1,"name":"math","description":"This is a math course."}');
alert(obj['name']);
Try this :) You can use JSON.parse insted of $.parseJSON if you are not using jquery. Following in Java
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);
}
Everything between the { } makes part of an array, so you first need to get a JSONArray like this:
JSONArray myJSONArray = obj.getJSONArray();
And then you can access the field values with:
myJSONArray.getString("name") etc...
Search on google how to work with JSONArray.

How to parse a deep URL using jQuery params()?

Building an Android app that needs to parse a URL built with deep parameters using jQuery params().
Sample URL:
http://webapp.example.com/#params%5Bid%5D=33330&type=detail&channel=ss&view=Detail
The result should be JSON, which I can feed into Gson. Manual parsing is not optimal; a generic solution is preferable.
How can this task be done?
at first glance I thought you need a js/jquery solution. But on closer inspection, probably java. Anywhoo, I had already dont the former so you get both!
Js/jquery
url="http://webapp.example.com/#params%5Bid%5D=33330&type=detail&channel=ss&view=Detail";
delimatedString = url.substring(url.indexOf("#")+1,url.length); //remove everything before the #
var jsonObject = new Object();
$.each(delimatedString.split("&"), function(index, item) {//for loop to spit at the *&
//item is now in the syntax key=value
var keyValPair = item.split("="); //split each item at the = to seperate
var key = keyValPair[0];
var value = keyValPair[1];
jsonObject[key]=value;
});
java
String delimatedStrings = url.substring("&"+1, url.length)
String[] keyValuePairs = delimatedString.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String keyValuePair : keyValuePairs)
{
String key = delimatedString.split("=")[0];
String value = delimatedString.split("=")[1];
map.put(key, value);
}
ps. I didnt compile the java, and you will need an external lib to take care of the map to JSON conversion.

How to get column names from HQL query&result to json with Key as columns

How to convert hql query result directly to Json.I tried this one
Query query=session.createQuery(SQLUtilsConstants.fQuery);
query.setParameter(StringConstants.TRPID, trId);
List list=query.list();
gson = new Gson();
String jsonStudents = gson.toJson(list);
System.out.println("jsonStudents = " + jsonStudents);
When i converted.I get a json with list of values without properties.Query result contains data from multiple table .I want to generate result with properties as key and value as output.If query contains customerid and customername then i need a result like this.
[{"customerid" : "abc", "customername" : "rose"}]
But using above code i getting like this..
[{"abc", "rose"}]
How can i do this???
You should create a Map, how ever you want it. then parse the map into json.
Map<String,WhatEver> newMap = new HashMap<String,WhatEver>();
foreach(WhatEver item: list){
//create your map how ever you like it to be
}
String jsonStudents = gson.toJson(newMap);

How to decode json without knowing the key/name string?

I am receiving a json string in the following format:
{"27":{"id":"27","uid":"4","title":"teamer.zapto.org","url":"www.google.jo","ip":"74.125.234.63","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058071"}},"fetch_interval":"60","ping_shift":"0"},
"30":{"id":"30","uid":"4","title":"google","url":"www.google.com","ip":"74.125.234.114","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058079"}},"fetch_interval":"60","ping_shift":"0"},
"31":{"id":"31","uid":"4","title":"facebook.com","url":"facebook.com","ip":"69.171.247.21","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058095"}},"fetch_interval":"60","ping_shift":"0"},
"32":{"id":"32","uid":"4","title":"ebir","url":"www.ebir.com","ip":"74.52.50.226","enabled":"1","services":{"Ftp":{"status":"1","ts":"1355058073"},"Http 1":{"status":"1","ts":"1355058073"}},"fetch_interval":"60","ping_shift":"0"},
"33":{"id":"33","uid":"4","title":"zapto","url":"teamer.zapto.org","ip":"200.35.150.6","enabled":"1","services":{"Http 1":{"status":"0","ts":"1355056146"}},"fetch_interval":"3600","ping_shift":"2"},
"35":{"id":"35","uid":"4","title":"vogella.com","url":"vogella.com","ip":"46.163.79.226","enabled":"1","services":{"Ftp":{"status":"1","ts":"1355058098"},"Http 1":{"status":"1","ts":"1355058098"}},"fetch_interval":"60","ping_shift":"0"},
"36":{"id":"36","uid":"4","title":"msn","url":"www.msn.com","ip":"131.253.13.140","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058103"}},"fetch_interval":"60","ping_shift":"0"},
"37":{"id":"37","uid":"4","title":"dubizzle.com","url":"www.dubizzle.com","ip":"94.236.93.152","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058068"}},"fetch_interval":"60","ping_shift":"0"},
"38":{"id":"38","uid":"4","title":"olx.jo","url":"olx.jo","ip":"204.74.99.100","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058108"}},"fetch_interval":"60","ping_shift":"0"},
"40":{"id":"40","uid":"4","title":"www.sukar.com","url":"www.sukar.com","ip":"72.52.8.195","enabled":"1","services":{"Ftp":{"status":"0","ts":"1355058092"},"Http 1":{"status":"1","ts":"1355058092"}},"fetch_interval":"60","ping_shift":"0"}}
as you can see the keys are numbers (27, 30, 31,...) and are not consecutive. How can I get the data from such json? I know that it must be some kind of loop depending on length but I couldn't figure it out on how to do so. Usually I'd use jObject.getString("id"), but since I don't know what the string would be what can I do?
If you have a JSONObject as the root, you should be able to do the following:
JSONObject root = new JSONObject(jsonString);
JSONArray names = root.names();
for(int i = 0; i < names.length(); i++) {
String tag = names.getString(i);
...
}
The tag will be the numeric tag you refer to.
JSONObject questionMark = new JSONObject(jsonString);
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);

Parse JSON object with string and value only

I have problem when trying to parse with minimum value to map in Android.
There some sample JSON format with more information ex:
[{id:"1", name:"sql"},{id:"2",name:"android"},{id:"3",name:"mvc"}]
This that example most common to use and easy to use just use getString("id") or getValue("name").
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"}
Thank
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);
}
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;

Categories

Resources