In the Result String i have entire data for that i'm parsing ,i need to print Current Conditions inside values.
current_condition": [ {"cloudcover": "75", "humidity": "71", "observation_time": "06:55 AM", "precipMM": "0.6", "pressure": "1009", "temp_C": "32", "temp_F": "90", "visibility": "10", "weatherCode": "116", "weatherDesc": [ {"value": "Partly Cloudy" } ], "weatherIconUrl": [ {"value": "http:\/\/cdn.worldweatheronline.net\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" } ], "winddir16Point": "S", "winddirDegree": "170", "windspeedKmph": "9", "windspeedMiles": "6" } ]
This is my json array ,here i need cloudcover ,weatherDescarrays inside values,how can i print those values.
Here what i did is
JSONParser parser = new JSONParser();
Object obj1 = parser.parse(Result);
JSONObject jobj = (JSONObject) obj1;
JSONObject dataResult = (JSONObject) jobj.get("data");
JSONArray current_condition = (JSONArray) dataResult.get("current_condition");
//out.println(current_condition);
for (int i = 0; i < current_condition.size(); i++) {
}
inside for loop how to repeat and print values ,could anybody help me,thanks in advance.
Assuming that you are using org.json, I would iterate over the array as follows:
public static void main(String[] args) {
String json = "{ \"data\": { \"current_condition\": [ {\"cloudcover\": \"75\", \"humidity\": \"71\", \"observation_time\": \"06:55 AM\", \"precipMM\": \"0.6\", \"pressure\": \"1009\", \"temp_C\": \"32\", \"temp_F\": \"90\", \"visibility\": \"10\", \"weatherCode\": \"116\", \"weatherDesc\": [ {\"value\": \"Partly Cloudy\" } ], \"weatherIconUrl\": [ {\"value\": \"http:\\/\\/cdn.worldweatheronline.net\\/images\\/wsymbols01_png_64\\/wsymbol_0002_sunny_intervals.png\" } ], \"winddir16Point\": \"S\", \"winddirDegree\": \"170\", \"windspeedKmph\": \"9\", \"windspeedMiles\": \"6\" } ]}}";
try {
JSONObject jObj = new JSONObject(json);
JSONObject dataResult = jObj.getJSONObject("data");
JSONArray jArr = (JSONArray) dataResult.getJSONArray("current_condition");
for(int i = 0; i < jArr.length();i++) {
JSONObject innerObj = jArr.getJSONObject(i);
for(Iterator it = innerObj.keys(); it.hasNext(); ) {
String key = (String)it.next();
System.out.println(key + ":" + innerObj.get(key));
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Are you using json simple?, if yes, then try :
for (JSONObject object : current_condition) {
System.out.println("cloudcover : " + object.get("cloudcover"));
System.out.println("humidity : " + object.get("humidity"));
}
Related
I have this json that i got using the YoutubeAPI :
{
"items": [
{
"id": {
"videoId": "ob1ogBV9_iE"
},
"snippet": {
"title": "13 estrellas ",
"description": "Pueden encontrar estas "
}
},
{
"id": {
"videoId": "o9vsXyrola4"
},
"snippet": {
"title": "Rayos Cósmicos ",
"description": "Este es un programa piloto "
}
}
]
}
i want to save the fiel "id" on an ArrayList but i have some problems this is the code im using:
JSONArray jsonArray = myResponse.getJSONArray("items");
In this line im creating an JSONarray with the JSONobject i created first
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
list.add(json.getString("videoID"));
} catch (JSONException e) {
e.printStackTrace();
}
}
My question is how can i access to this field? and how can i save it
You've got two main issues. The first is that "videoID" and "videoId" are not the same string. So you're checking for a key that doesn't exist.
Your second problem is that the "videoId" key doesn't exist in the top level object, it's inside the "id" object, so you need to drill down an extra layer to get it:
JSONArray jsonArray = myResponse.getJSONArray("items");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
JSONObject id = json.getJSONObject("id");
list.add(id.getString("videoId"));
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println(list); // [ob1ogBV9_iE, o9vsXyrola4]
Try with correct case for videoId, like
list.add(json.getString("videoId"));
I try to create a desired json structure in java but I get only last value in json structure since i creating json outside for loop. if i create it in nested for loop then its not give me desired structure of json.
My code is here:-
public static void main(String[] args) {
JSONObject TP1 = new JSONObject();
String[] alias = {"topping","cake"};
String[] entityType = {"Topping","cake"};
String[] textString = {"pizza","pancake"};
String[] usersays_text = {"I want ","I want "};
for(String usy:usersays_text)
{
TP1.put("text",usy.toString());
}
JSONObject TP2 = new JSONObject();
for(String tS:textString)
{
TP2.put("text",tS.toString());
}
for(String eT:entityType)
{
TP2.put("entityType",eT.toString());
}
for(String al:alias)
{
TP2.put("alias",al.toString());
}
JSONArray JSA=new JSONArray();
JSA.put(TP1);
JSA.put(TP2);
JSONObject root1= new JSONObject();
root1.put("parts", JSA);
JSONArray JSA4=new JSONArray();
JSA4.put(root1);
JSONObject root3= new JSONObject();
root3.put("TP", JSA4);
//To print
JSONObject json = new JSONObject(root3.toString()); // Convert text to object
System.out.println(json.toString(4));
}
which results me following json structure:-
{
"TP": [{
"parts": [{
"text": "I want "
},
{
"entityType": "cake",
"alias": "cake",
"text": "pancake"
}
]
}]
}
Desired structure for each value of string array -
for ex:
{
"TP": [
{
"parts": [
{
"text": "I want "
},
{
"alias": "topping",
"text": "pizza",
"entityType": "Topping"
}
]
},
{
"parts": [
{
"text": "I want "
},
{
"alias": "cake",
"entityType": "cake",
"text": "pancake"
}
]
}
]
}
Your jsonobject construction is wrong. In 'jsonobject' key is in unique,
when you try it like this
for(String usy:usersays_text)
{
TP1.put("text",usy.toString());
}
the same key is present in the json object and values get replaced.
Please try the below code, it constructs the json object as expected.
public static void main(String args[]) {
JSONObject TP1 = new JSONObject();
String[] alias = {"topping","cake"};
String[] entityType = {"Topping","cake"};
String[] textString = {"pizza","pancake"};
String[] usersays_text = {"I want ","I want "};
JSONObject jobj = new JSONObject();
JSONArray jarr = new JSONArray();
for(int index = 0; index < usersays_text.length; index++)
{
JSONObject parts = new JSONObject();
JSONArray partsArr = new JSONArray();
JSONObject partsObj = new JSONObject();
partsObj.put("text", usersays_text[index].toString());
JSONObject cont = new JSONObject();
cont.put("alias", alias[index].toString());
cont.put("text", textString[index].toString());
cont.put("entityType", entityType[index].toString());
partsArr.put(partsObj);
partsArr.put(cont);
parts.put("parts", partsArr);
jarr.put(parts);
}
jobj.put("trainingPhrases", jarr);
System.out.println(jobj.toString(4));
}
You have to use single loop, Assume each array has same length, Following code could help you
public static void main(String[] args) throws Exception {
String[] alias = {"topping", "cake"};
String[] entityType = {"Topping", "cake"};
String[] textString = {"pizza", "pancake"};
String[] usersays_text = {"I want ", "I want "};
JSONArray parts = new JSONArray();
for (int i = 0; i < usersays_text.length; i++) {
JSONArray JSA = new JSONArray();
JSONObject TP1 = new JSONObject();
TP1.put("text", usersays_text[i]);
JSONObject TP2 = new JSONObject();
TP2.put("text", textString[i]);
TP2.put("entityType", entityType[i]);
TP2.put("alias", alias[i]);
JSA.put(TP1);
JSA.put(TP2);
parts.put( JSA);
}
JSONObject partsObject = new JSONObject();
partsObject.put("parts",parts);
JSONObject root= new JSONObject();
root.put("trainingPhrases", partsObject);
//To print
JSONObject json = new JSONObject(root.toString()); // Convert text to object
System.out.println(json.toString(4));
}
{
"hits": [
{
"name": "Google",
"results": [
{
"count": 27495
}
]
},
{
"name": "Yahoo",
"results": [
{
"count": 17707
}
]
}
}
i'am able to read the name and results from the above json by the below code, but unable to print the count value alone from JSON.
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
if(null!=jsonObject.get("hits"))
{
System.out.println("Inside IF...");
JSONArray ja = (JSONArray) jsonObject.get("hits");
for(int i=0;i<ja.size() ; i++)
{
System.out.println("Inside FOR...");
JSONObject tempJsonObj = (JSONObject) ja.get(i);
System.out.println(tempJsonObj.get("name").toString());
System.out.println(tempJsonObj.get("results").toString());
}
}
How to extract an array of JSON inside JSON array
Just as you parsed for Outer JSONArray (hits ) . Follow the same for inner ("results") :
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
if(null!=jsonObject.get("hits"))
{
System.out.println("Inside IF...");
JSONArray ja = (JSONArray) jsonObject.get("hits");
for(int i=0;i<ja.size() ; i++)
{
System.out.println("Inside FOR...");
JSONObject tempJsonObj = (JSONObject) ja.get(i);
System.out.println(tempJsonObj.get("name").toString());
System.out.println(tempJsonObj.get("results").toString());
JSONArray innerarray = (JSONArray) tempJsonObj.get("results");
for(int i=0;i<innerarray.size() ; i++)
{
JSONObject tempJsoninnerObj = (JSONObject) innerarray.get(i);
System.out.println(tempJsoninnerObj.get("count").toString());
}
}
}
I am getting the following as a String response from a webserveice:
[
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
]
In Java I am trying to do the following:
JSONArray jArray = new JSONArray(result);
System.out.println("Response: "+jArray);
for(int i = 0; i<= jArray.length(); i++){
try {
JSONObject oneObject = jArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
However I am getting the following exception:
JSON Exception: org.json.JSONException: Value
[
{
"dgtype": "adhoc",
"subtypename": "Person",
"subtypedesc": "null",
"summary": "Junaid (Self)",
"subtype": "person",
"birthdate": "1995-1-23 ",
"name": "Junaid (Self)"
},
{
"dgtype": "adhoc",
"subtypename": "Job",
"subtypedesc": "null",
"summary": "Exa",
"subtype": "person",
"birthdate": "2010-01-30",
"name": "Junaid (Self)"
}
]
at 0 of type org.json.JSONArray cannot be converted to JSONObject
JSON Exception: org.json.JSONException: Index 1 out of range [0..1)
I am following this example. Where am I going wrong? Also notice the missing long brackets in the exception snippet.
You have two arrays, one is within another:
[
[
//Your objects
]
]
You could either change data format so it only has one array, or modify your code:
JSONArray outer = new JSONArray(result);
JSONArray jArray = outer.getJSONArray(0);
jArray JSONArray contain another JSONArray which contain JSONObeject so first get JSONArray and then get all JSONObject from it:
JSONArray oneArray = jArray.getJSONArray(i);
for(int j = 0; j<= oneArray.length(); j++){
JSONObject oneObject = oneArray.getJSONObject(j);
// get dgtype,subtypename,subtypedesc,.. from oneObject
}
As it says, 'JSONArray cannot be converted to JSONObject', You have an array in another array, so
JSONArray jArray1 = new JSONArray(result);
then
JSONArray jArray = jArray1.getJSONArray(0);
Now it will work.
for(int i = 0; i<= jArray.length(); i++){
final JSONArray innerArray = jArray.getJSONArray(i);
for (int a = 0; a < innerArray.length(); a++) {
try {
final JSONObject oneObject = innerArray.getJSONObject(i);
String dgtype = oneObject.getString("dgtype");
String subtypename = oneObject.getString("subtypename");
String subtypedesc = oneObject.getString("subtypedesc");
String summary = oneObject.getString("summary");
String subtype = oneObject.getString("subtype");
String birthdate = oneObject.getString("birthdate");
String name = oneObject.getString("name");
System.out.println(i);
System.out.println("dgtype: "+dgtype);
System.out.println("subtypename: "+subtypename);
System.out.println("subtypedesc: "+subtypedesc);
System.out.println("summary: "+summary);
System.out.println("subtype: "+subtype);
System.out.println("birthdate: "+birthdate);
System.out.println("name: "+name);
} catch (JSONException e) {
System.out.println("JSON Exception: "+e);
}
}
}
This question already has answers here:
Android how to sort JSONArray of JSONObjects
(6 answers)
Closed 9 years ago.
How to sort a JSONArray of objects by object's field?
Input:
[
{ "ID": "135", "Name": "Fargo Chan" },
{ "ID": "432", "Name": "Aaron Luke" },
{ "ID": "252", "Name": "Dilip Singh" }
];
Desired output (sorted by "Name" field):
[
{ "ID": "432", "Name": "Aaron Luke" },
{ "ID": "252", "Name": "Dilip Singh" }
{ "ID": "135", "Name": "Fargo Chan" },
];
Try this:
//I assume that we need to create a JSONArray object from the following string
String jsonArrStr = "[ { \"ID\": \"135\", \"Name\": \"Fargo Chan\" },{ \"ID\": \"432\", \"Name\": \"Aaron Luke\" },{ \"ID\": \"252\", \"Name\": \"Dilip Singh\" }]";
JSONArray jsonArr = new JSONArray(jsonArrStr);
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonValues = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArr.length(); i++) {
jsonValues.add(jsonArr.getJSONObject(i));
}
Collections.sort( jsonValues, new Comparator<JSONObject>() {
//You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME = "Name";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_NAME);
valB = (String) b.get(KEY_NAME);
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
//if you want to change the sort order, simply use the following:
//return -valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArr.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
The sorted JSONArray is now stored in the sortedJsonArray object.