How to decode json without knowing the key/name string? - java
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);
Related
How to put an value to the extracting JSON and display it
I wanna display a parsed json with my values . I mean , I wanna add some values to the json and display it . I can display all result from respond , but I wanna display just the json with my values not all data :) here i have parsed allready my json JSONObject jsonObject = new JSONObject(adresUrl); JSONArray offerResources = jsonObject.getJSONArray("offerResources"); for(int y = 0; y < offerResources.length(); y++){ JSONObject currentTransfer = offerResources.getJSONObject(y); JSONArray meetPoint = currentTransfer.getJSONArray("meetPoints"); for (int i = 0; i < meetPoint.length(); i++){ JSONObject currentMeetPoints = meetPoint.getJSONObject(i); String startAddress = currentMeetPoints.getString("startAddress"); // here i wanna put some values , but i dont know how // here is a litle piece of my json :) "meetPoints": [ { "startAddress": "....", // after the collon i have to put my value . "startLocation": { thank you for your help
I'm not sure if I understood your question fully but from what I got here is some solution. I simply created a string and couple of Json objects and jsonarray for adding the list of values and put it inside the main json object "jsonValueObject " and accumulate it inside meetPoints. Accumulate(String key,Object Value) is a key value pair, meaning if key is created then Object is checked for being an array,and if this array has "values", it will be added else new array will be created. "Put" will replace the value if the key exists. String jsonString = "{\"results\":[{\"Country\":\"value\",\"state\":\"value\" }, { \"Country\":\"value\", \"state\":\"value\"}]}"; JSONObject meetPoints = new JSONObject(jsonDataString); JSONObject jsonValueObject = new JSONObject(); JSONArray list = new JSONArray(); jsonValueObject.put("Country", "newValue"); jsonValueObject.put("state", "newValue"); jsonValueObject.put("city", "Chennai"); jsonValueObject.put("street", "Bharathiyar Street"); jsonValueObject.put("date", "14May2017"); jsonValueObject.put("time", "10:00AM"); list.put(jsonValueObject); meetPoints.accumulate("values", list); System.out.println(meetPoints);
Get the count of entries from a json file
I am trying to get json data from a fake api call and need to get the count of the items in it(so that in future I can call the actual restful service). I am not able to get the number of departments in the json. I am expecting the result as 4(int) here. I am not able to get the string value(json) for the code below: String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class); Please find below the entire code: String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class); JSONObject jsnobject = new JSONObject(json); JSONArray jsonArray = jsnobject.getJSONArray("locations"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject explrObject = jsonArray.getJSONObject(i); } JSON Sample: { "Department": [ {"SectionId":"1","SectionName":"Childrens Wear"}, {"SectionId":"2","SectionName":"Womens Wear"}, {"SectionId":"3","SectionName":"F&A"}, {"SectionId":"1","SectionName":"Mens Wear"} ] } I am new to java as well as api's. Thanks,
You are either using incorrect key in code or you posted incorrect JSON example. You used locations as the key incode however there is no value against that key in sample JSON. You need to use Department as the key. JSONArray jsonArray = jsnobject.getJSONArray("Department");
Getting Json object inside a Json object in Java
So I have some code that is able to send this out: {"id":1, "method":"addWaypoint", "jsonrpc":"2.0", "params":[ { "lon":2, "name":"name", "lat":1, "ele":3 } ] } The server receives this JSON object as a string named "clientstring": JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject String method = obj.getString("method"); //Pulls out the corresponding method Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method". however both of these have given me exceptions: String params = obj.getString("params"); and JSONObject params = obj.getJSONObject("params"); I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? I dont understand. Any help is VERY appreciated, thanks!
params in your case is not a JSONObject, but it is a JSONArray. So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject. JSONObject obj = new JSONObject(clientstring); JSONArray params = obj.getJsonArray("params"); JSONObject param1 = params.getJsonObject(0);
How try like that JSONObject obj = new JSONObject(clientstring); JSONArray paramsArr = obj.getJSONArray("params"); JSONObject param1 = paramsArr.getJSONObject(0); //now get required values by key System.out.println(param1.getInt("lon")); System.out.println(param1.getString("name")); System.out.println(param1.getInt("lat")); System.out.println(param1.getInt("ele"));
Here "params" is not an object but an array. So you have to parse using: JSONArray jsondata = obj.getJSONArray("params"); for (int j = 0; j < jsondata.length(); j++) { JSONObject obj1 = jsondata.getJSONObject(j); String longitude = obj1.getString("lon"); String name = obj1.getString("name"); String latitude = obj1.getString("lat"); String element = obj1.getString("ele"); }
simpleJson parsing in Java
I'm very new to parsing JSON. I have looked all over and cannot seem to grasp the idea to my particular problem. I'm having a hard time understanding how to get a JSON object from a JSON array. My example is below [{"styleId":94, "status":"verified", "abv":"4.2", "name":"Bud Light"}] Here is my current code JSONParser parser = new JSONParser(); Object obj = parser.parse(inputLine); JSONObject jsonObject = (JSONObject) obj; Long currPage = (Long)jsonObject.get("currentPage"); System.out.println(currPage); JSONArray jArray = (JSONArray)jsonObject.get("data"); System.out.println(jArray); inputLine is my orignal JSON. I have pulled a JSONArray out of the original JSONObject that has the "data" tag. Now this is where I'm stuck and given the JSONArray at the top. Not sure how to iterate through the Array to grab JUST the "name" tag. Thanks for the help in advanced!
To iterate in a JSONArray you need to go through each element in a loop. int resultSize = jArray.length(); JSONObject result; for (int i = 0; i < resultSize; i++) { result = resultsArray.getJSONObject(i); String name = result.getString("name"); // do whatever you want to do now... }
just use Gson . it works well out of the box with any object type you supply. This is an example from the user's guide: int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
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;