How to Parse JSON Data like array-->Object-->Object with value - java

I'm New to android development. I just know very little about JSON. I used Json simple format.
{
"worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
},
{
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":"http://www.androidbegin.com/tutorial/flag/india.png"
}
]
}
In above JSON data we can simply call rank, country after getting JSOn array worldpopulation.
Now I have JSON data showed below, here JSON array is same I think since item is present I don't know. Then it has objects as numbers under that it has country.
{
"Items":"0 to 2",
"worldpopulation":[
{
"0":{
"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
}
},
{
"1":{
"country":"India",
"population":"1,210,193,422",
"flag":"http://www.androidbegin.com/tutorial/flag/india.png"
}
}
]
}
Now I don't know how to call country, population and flag.
Is it same method as. Jsonobject.getstring("rank"); after jsonarray("worldpopulation");
Or different.

Do as following
try {
JSONObject reader = new JSONObject("your json str");
JSONArray items = reader.getJSONArray("worldpopulation");
for (int i = 0; i < items.length(); ++i) {
JSONObject jsonProgram = items.getJSONObject(i);
JSONObject yourObject = null;
if (i == 0) {
yourObject = jsonProgram.getJSONObject("0");
} else {
yourObject = jsonProgram.getJSONObject("1");
}
//Do here what did before with yourObject
}
} catch (JSONException e) {
Log.i("Test", e.toString());
}

Related

Easiest way to parse a triple nested JSON?

I am given a JSON that will come in this format:
"template":{
"mod1":[
{
"param1":"55",
"param2":"5",
"param3":"somedata"
}
],
"mod2":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod3":[
{
"param1":"somedata",
"param2":"somedata",
"param3":"somedata"
}
],
"mod4":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod5":[
{
"param1":"somedata"
}
]
}
}
What is the easiest way to parse it? What I'd like is to get the params inside the mod and their associated values together, to store into a database. The way I am doing it is as so:
JSONObject obj = new JSONObject(json);
System.out.println(obj);
Iterator<String> keys = obj.keys();
while(keys.hasNext()) {
String key = keys.next();
JSONObject currTemplate = (JSONObject) obj.get(key);
if(currTemplate instanceof JSONObject) {
System.out.println("LIST OF ALL MODULES : " + currTemplate);
Iterator<String> currObjKeys = ((JSONObject) currTemplate).keys();
while(currObjKeys.hasNext()) {
String currObjKey = currObjKeys.next();
System.out.println("MODULE: " + currObjKey);
JSONArray array = currTemplate.getJSONArray(currObjKey);
System.out.println("ARRAY: " + array);
for(int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
String[] names = JSONObject.getNames(object);
for(String name: names) {
System.out.println("PARAMS");
System.out.println(name);
System.out.println(object.get(name));
}
}
}
}
And it currently prints what I need correctly. What I am asking is if there is a more efficient way to do it - the way I currently have it is O(N^4), and I was wondering if anyone had any idea to parse the JSON in a more efficient way. Note: the params will not always be in form param1, param2, the names will always be different. Just changed it for confidentiality sake.
Thank you in advance.

How can I extract a specific part of a JSON file?

This is my JSON file :
{
"coord":{
"lon":139,
"lat":35
},
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F04n.png?1499366020983"
}
],
"base":"stations",
"main":{
"temp":7,
"pressure":1025,
"humidity":75,
"temp_min":7,
"temp_max":7
},
"visibility":10000,
"wind":{
"speed":5.1,
"deg":100
},
"clouds":{
"all":75
},
"dt":1549794600,
"sys":{
"type":1,
"id":8024,
"message":0.0034,
"country":"JP",
"sunrise":1549748122,
"sunset":1549786891
},
"id":1851632,
"name":"Shuzenji",
"cod":200
}
I have tried to extract the weather array but it doesn't work.
JSONArray mArray;
try {
mArray = new JSONArray(result);
for (int i = 0; i < mArray.length(); i++) {
JSONObject mJsonObject = mArray.getJSONObject(i);
txtJson.append(mJsonObject.getString("weather"));
}
} catch (JSONException e) {
e.printStackTrace();
//txtJson.setText(result);
}
txtJson.setText(result);
}
I don't know what you expect that code to do, but if you want to extract the weather array, this is how you do it.
JSONObject json = new JSONObject(result);
JSONArray weather = json.getJSONArray("weather");
Then you can get individual entries in the array
JSONObject entry = weather.getJSONObject(0);
int id = entry.getInt("id");
String main = entry.getString("main");
or if you just want to turn the array back to a string
String s = weather.toString();

Finding length of nested json array in Java

I have a junk of json that has a nested json array inside of it. What would be the best way to get that nested json out and then get the length of it. I want to get the two fields inside of "/details" then use them
{
"Lane2":[
{
"authHost":"host.com",
"action-items":[
{
"/details":[
{
"path":"/something/details",
"httpMethod":"get"
}
]
},
{
"/summary":[
{
"path":"/something/summary",
"httpMethod":"get"
}
]
},
{
"/summary":[
{
"path":"/action-items/summary",
"httpMethod":"get"
}
]
}
]
}
]
}
I agree use the JSON parser, here's a simple example if you want to try on your own:
public String[] parseJA(JSONArray input, String[] key) throws JSONException{
// Parses a JSONArray with matching KEY value into a Sring[]
output = new String[input.length()];
joOutput = new JSONObject[input.length()];
for(int i = 0; i < input.length();++i) {
output[i] = input.getString(i);
joOutput[i] = input.getJSONObject(i);
output[i] = joOutput[i].getString(key[i]);
}
return output;
}

JSON parse Android - object in object

How to parse this json? I want get data from title, field_place and brothers fields.
{
"events": [
{
"event": {
"title": "BITUMIX Martyna Jastrz\u0119bska",
"field_place": "Nowe Miejsce Al Jerozolimskie 51 lok.2",
"field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/martyna_jastrzebska_bitumix_2.jpg?itok=nd2O5U5z"
}
},
{
"event": {
"title": "Wiecz\u00f3r Komedii Improwizowanej - D\u017cem Impro!",
"field_place": "",
"field_zdjecie": "http:\/\/wybierzkulture.waw.pl\/sites\/default\/files\/styles\/post\/public\/dzem_17_maja.jpg?itok=bfgDYxKq"
}
},
...
I tried:
JSONObject itemm = jArray.getJSONObject(i);
JSONObject oneObject = itemm.getJSONObject("event");
String title = oneObject.getString("title");
String field_place = oneObject.getString("field_place");
... but it doesn't work.
In a JSON string , there are two symbols that guide you through parsing :
{ - indicates a JSONObject
[ - indicates a JSONArray
When parsing a json string, you should go through this items iteratively. To understand how many JsonObjects and JsonArrays you have in your string , and from which you should start parsing, use a json-visualizer tool like this website. :
Example : As you see, the root object is a JSONObject which consists of an JSONArray with three jsonOnjects. To parse such a structure you can use :
JSONObject jsonobj = new JSONObject(jsonstring);
String result = jsonObject.getString("success");
String error_number = jsonObject.getString("error_number");
String error_message = jsonObject.getString("error_message");
JSON Array jsonarray = jsonobj.getJSONArray();
String[] names = new String[jsonArray.length()];
String[] formattedNames = new String[jsonArray.length()];
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
names [i] = jsonObject.getString("name");
formattedNames [i] = jsonObject.getString("formattedName");
}
try this
JSONArray element = jsonobj.getJSONArray("events");
for(int i=0;i < element.length();i++){
JSONObject e = element.getJSONObject(i);
Log.d("TESTTT22",e.getJSONObject("event").getString("title"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to convert JSON formatted string of data rows of a table in to java array in android

I have a JSON string like this of data for a table in an android app. one of {} is a row of data for the table. I want to separate these {}s into an array and then each element inside this array into other sub-arrays separating other elements inside {}. Please suggest an appropriate way of accomplishing this criteria using JSON. Thank you.
[
{
"nodeName":"prime_mtsc22#smpp3",
"nodeId":"MTSC3",
"tidPrefix":"4",
"optStatus":"offline",
"daStart":"1",
"daEnd":"3",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp2",
"nodeId":"MTSC58",
"tidPrefix":"1",
"optStatus":"blocked",
"daStart":"5",
"daEnd":"10",
"description":"new description"
},
{
"nodeName":"prime_mtsc22#smpp1",
"nodeId":"MTSC1",
"tidPrefix":"15",
"optStatus":"online",
"daStart":"12",
"daEnd":"20",
"description":"Description"
},
{
"nodeName":"prime_mtsc22#smpp0",
"nodeId":"MTSC15",
"tidPrefix":"15",
"optStatus":"offline",
"daStart":"25",
"daEnd":"30",
"description":"Description"
}
]
ok so in that case the code to use is this
String jsonString = <your jsonString>;
// THIS IS NOT NEEDED ANYMORE
//JSONObject json = new JSONObject(jsonString);
JSONArray topArray = null;
try {
// Getting your top array
// THIS IS NOT NEEDED ANYMORE
//topArray = json.getJSONArray(jsonString);
//use this instead
topArray = new JSONArray(jsonString);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
ok?
Use JSONObject for this http://developer.android.com/reference/org/json/JSONObject.html
Example
String jsonString = <your jsonString>;
JSONObject json = new JSONObject(jsonString);
JSONObject topArray = ;
try {
// Getting your top array
topArray = json.getJSONArray(TAG_ARRAY_TOP);
// looping through All elements
for(int i = 0; i < topArray.length(); i++){
JSONObject c = topArray.getJSONObject(i);
//list holding row data
List<NodePOJO> nodeList = new ArrayList<NodePOJO>();
// Storing each json item in variable
String nodeName = c.getString("nodeName");
String nodeID = c.getString("nodeID");
NodePOJO pojo = new NodePOJO();
pojo.setNodeName(nodeName);
//add rest of the json data to NodePOJO class
//the object to list
nodeList.add(pojo);
}
} catch (JSONException e) {
e.printStackTrace();
}
Use the NodePOJO class to hold each row values.
public class NodePOJO {
private String nodeName;
// do for rest of the json row data
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public String getNodeName() {
return this.nodeName;
}
}

Categories

Resources