How to access nested elements of JSON data in Java? - java

I'm getting JSON data from a url and I want to show the data on my website. I am successfully showing all JSON data except JSON Hierarchy (JSON Object) data. I am able to access JSONArray person and error data. But, I am not able to access hierarchy (JSON Object) updated data.
I want to access updated.time.
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
{
"person": [
{
"name": "John",
"city": "Mumbai"
},
{
"name": "Rahul",
"city": "Delhi"
},
{
"name": "Sanjana",
"city": "Amritsar"
},
{
"name": "Anjali",
"city": "Hyderabad"
},
{
"name": "Mukund",
"city": "Bangalore"
},
{
"name": "Raunak",
"city": "Patna"
}
],
"updated": {
"time": "14:17:48",
"date": "2016-04-10"
},
"error": "2353"
}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the error
System.out.println(genreJsonObject.get("error"));
//Get Array Values
JSONArray genreArray = (JSONArray) genreJsonObject.get("person");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("name"));
// get the Second
JSONObject firstGenre = (JSONObject) genreArray.get(1);
System.out.println(firstGenre.get("name"));
// get the third
JSONObject firstGenre = (JSONObject) genreArray.get(2);
System.out.println(firstGenre.get("city"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}

This json Result appears what you got from your api URL . Right ??
{
"person":[
{
"name":"John",
"city":"Mumbai"
},
{
"name":"Rahul",
"city":"Delhi"
},
{
"name":"Sanjana",
"city":"Amritsar"
},
{
"name":"Anjali",
"city":"Hyderabad"
},
{
"name":"Mukund",
"city":"Bangalore"
},
{
"name":"Raunak",
"city":"Patna"
}
],
"updated":{
"time":"14:17:48",
"date":"2016-04-10"
},
"error":"2353"
}
Now Here is a Code how to Iterate or parse your json Object. I Suppose that above Result json is stored in a String Variable String genreJson as per Your Code.
Here I wrote a method to solve your Problem. You may take a reference of it and may try your own code.
public void testYourJSON(String genreJson){
JSONParser parser=new JSONParser(); //parser used to parse String to Correct Json format.
JSONObject obj_ComplexData = (JSONObject) parser.parse(genreJson); // Now Your String Converted to a JSONObject Type.
//person tag Array Data is fetched and Stored into a JSONArray Object.
JSONArray obj_arrayPersonData = (JSONArray) parser.parse(obj_ComplexData.get("person").toString());
for (Object person : obj_arrayPersonData ) { //Iterate through all Person Array.
System.out.println(person.get("name"));
System.out.println(person.get("city"));
}
//Select "updated" Tag Json Data.
JSONObject obj_Updated = (JSONObject) parser.parse(obj_ComplexData.get("updated").toString());
System.out.println(obj_Updated.get("time")); //display time tag.
System.out.println(obj_Updated.get("date")); //display date tag.
System.out.println(obj_Updated.get("error")); //display Your Error.
}

Try this
public static String[] getInfo(String url)
{
String result=//I am assuming your json response is in result
String[] titles=null;
try {
JSONObject jsonObject=new JSONObject(result);
JSONObject temp=null;
JSONArray jsonArray=jsonObject.getJSONArray("person");
int length=jsonArray.length();
person=new String[length];
for (int i=0;i<length;i++){
temp= (JSONObject) jsonArray.get(i);
titles[i]=temp.getString("name")+temp.getString("city");
}
} catch (JSONException e) {
e.printStackTrace();
}
return titles;
}
This works fine, if you face any problem write in comments.
Happy coding!!

Related

How to add subnode to json file using json-simple

I create json file with the folloing code:
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
public class CreatingJSONDocument {
public static void main(String args[]) {
//Creating a JSONObject object
JSONObject jsonObject = new JSONObject();
//Inserting key-value pairs into the json object
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
try {
FileWriter file = new FileWriter("E:/output.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("JSON file created: "+jsonObject);
}
}
OUTPUT:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1"}
How can I add content of java map to the this json output as a new node sothat I have at the end the following output:
JSON file created: {
"First_Name":"Shikhar",
"ID":"1",
"data": {
"a": "Test1",
"b": "Test2"
}
}
You just need to add another object of type JsonObject and it will do that
//...
jsonObject.put("ID", "1");
jsonObject.put("First_Name", "Shikhar");
jsonObject.put("data", new JSONObject(data));
//...
And that will return the output what you want
In case you need add more fields without a object a good practice its do the next:
JSONObject mainFields = new JSONObject();
mainFields.put("id", "1");
JSONObject secondFields = new JSONObject();
secondFields.put("field1", "some cool");
secondFields.put("field2", "not cool");
mainFields.put("data", secondFields);
This return:
{
"id":"1",
"data":{
"field1": "some cool",
"field2": "not cool"
}
}

Parsing arrays in Json using Gson

Parsing arrays in json using Gson.
I have this following json and trying to parse it.
{
"success": true,
"message": "success message",
"data": [
{
"city": "cityname",
"state": "statename",
"pin": 0,
"name" :{
"firstname" : "user"
},
"id" :"emailid"
}],
"status" : "done"
}
So, I have created pojo classes using http://www.jsonschema2pojo.org/
Now, I want to parse the array, for value "city".This is how I did but not sure what is wrong here.
Gson gson = new Gson();
Records obj = gson.fromJson(response,Records.class);
try {
JSONArray jsonArray = new JSONArray(obj.getData());
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String city = object.getString("city");
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(city);
dialog.show();
}}
catch (Exception e) {
e.printStackTrace();
}
And this is what getData() is defined in model class:
public class Records {
//////
private ArrayList<Datum> data = null;
public ArrayList<Datum> getData() {
return data;
}
this is not required:
try {
JSONArray jsonArray = new JSONArray(obj.getData());
...
}
catch
...
you just need to do
Records obj = gson.fromJson(response,Records.class);
and then
obj.getData();
would be great if you check that getData() is not null, beacuse something xould go wrong when deserialising
for getting the city: use the getter in the Datum class, you have at the end a list of those obejcts when you call getData
public String getCity() {
return city;
}

JSONObject in Android

Here i want to fetch the data from the json, but i am getting only first two objects value (25, 44) but the ids are 50,60 . I don't know whats wrong with this code.
Below is my response from the server:
{
"product": {
"25": {
"training": "First Name",
"taken": null,
"date": "1386737285",
"body":"http://abc.xyz.in/video1.mp4",
"image": "http://abc.xyz.in/video1.jpg"
},
"44": {
"training": "Second Name",
"taken": null,
"date": "1389951618",
"body":"http://abc.xyz.in/video2.mp4",
"image":"http://abc.xyz.in/video2.jpg"
},
"50": {
"training": "Third Name",
"taken": null,
"date": "1389971004",
"body":"http://abc.xyz.in/video3.mp4",
"image": "http://abc.xyz.in/video3.jpg"
},
"60": {
"training": "Fourth Name",
"taken": null,
"date": "1390003200",
"body": "http://abc.xyz.in/video4.mp4",
"image": "http://abc.xyz.in/video4.jpg"
}
}
}
Here is the code for fetching data from json:
public String[] getDataFromResponse(String jsonProfileResponse,String secondParam,
String attributeName ) {
String[] attributeValue = null;
try {
json = new JSONTokener(jsonProfileResponse).nextValue();
if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
JSONObject jObj = jsonObject.getJSONObject(secondParam);
System.out.println(jObj);
Iterator<?> keys = jObj.keys();
List<String> listitems = new ArrayList<String>();
List<String> nids = new ArrayList<String>();
while (keys.hasNext()) {
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys
.next()));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
attributeValue = listitems.toArray(new String[0]);
trainingId = nids.toArray(new String[0]);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
return attributeValue;
}
Thanks for the considering...
Inside the hasNext you call twice keys.next()
So, instead of
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys.next()));
you have to do
String currentKey = String.valueOf(keys.next());
nids.add(currentKey);
JSONObject jsonObj = jObj.getJSONObject(currentKey);
String key="";
while (keys.hasNext()) {
key= keys.next()
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(key));
nids.add(key));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
use of key.next() twice is problem
because in JSONObject, the order of the keys is undefined.
#see: http://developer.android.com/reference/org/json/JSONObject.html#keys%28%29
try to sort your data on server, then response it in JSONArray

Parse multiple items in JSON into an array

I have a client that retrieves some json from this page. The json content looks like this:
{
"0": {
"name": "McDonalds 2",
"address": "892 West 75th Street, Naperville, IL 60540"
},
"1": {
"name": "McDonalds 1",
"address": "1298 South Naper Boulevard, Naperville, IL 60540"
},
"2": {
"name": "Burger King 1",
"address": "2040 Aurora Avenue, Naperville, IL, 60540"
}
}
I'm having problems parsing it. I always get an exception when trying to parse anything. It's my first time doing json so I might be doing something really bad. This is my code:
public static void parse(String jsonData)
{
JSONObject jsonObject = new JSONObject();
try
{
jsonObject = new JSONObject(jsonData);
}
catch (JSONException e)
{
e.printStackTrace();
}
try
{
// exception happens here when trying to access data
JSONObject name = ((JSONArray)jsonObject.get("0")).getJSONObject(0)
.getJSONObject("name");
JSONObject address = ((JSONArray)jsonObject.get("0")).getJSONObject(0)
.getJSONObject("address");
} catch (JSONException e) {}
}
How an I retrieve the name and address of each json item to convert it into a restaurant object?
The format of the JSON is wrong. Please refer to this link and the right code is below. You will know what to do.
public static void parse(String jsonData) {
ArrayList<Restaurant> restaurantList= new ArrayList<Restaurant>();
JSONObject jsonObject;
JSONObject jsonRestaurant;
try {
jsonObject= new JSONObject(jsonData);
for(int i=0;i<3;i++) {
Restaurant restaurant= new Restaurant();
jsonRestaurant= jsonObject.getJSONObject(Integer.toString(i));
restaurant.name= jsonRestaurant.getString("name");
restaurant.address= jsonRestaurant.getString("address");
restaurantList.add(restaurant);
}
}
catch(JSONException e) {
e.printStackTrace();
}
}

How to loop through json data in android

As mentioned in the title. How can I loop through my json data that I am getting from server. My getting this kind of json data
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Saleem",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Name",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
{
"tag":"home",
"success":1,
"error":0,
"uid":"4fc8f94f1a51c5.32653037",
"name":"Name",
"profile_photo":"http:\/\/example.info\/android\/profile_photos\/profile1.jpg",
"places":
{
"place_photo":"http:\/\/example.info\/android\/places_photos\/place1.jpg",
"created_at":"2012-06-02 00:00:00",
"seeked":"0"
}
}
here is where I am getting my json data
public class Home extends Activity {
Button btnLogout;
ScrollView svHome;
UserFunctions userFunctions;
LoginActivity userid;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
userid = new LoginActivity();
svHome = (ScrollView)findViewById(R.id.svHome);
setContentView(R.layout.home);
userFunctions = new UserFunctions();
/***********************************************************/
//here is where my above mentioned json data is
JSONObject json = userFunctions.homeData();
try {
if(json != null && json.getString("success") != null) {
//login_error.setText("");
String res = json.getString("success");
//userid = json.getString("uid").toString();
if(Integer.parseInt(res) == 1) {
//currently this only shows the first json object
Log.e("pla", json.toString());
} else {
//login_error.setText(json.getString("error_msg"));
}
} else {
Toast.makeText(getBaseContext(), "No data", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
/*******************************************************/
}
}
Update
After make changes accroding to the link given in the answer. Here are my changes
/***********************************************************/
JSONObject json = userFunctions.homeData();
String jsonData = json.toString();
try {
if(json != null && json.getString("success") != null) {
//login_error.setText("");
String res = json.getString("success");
//userid = json.getString("uid").toString();
if(Integer.parseInt(res) == 1) {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.e("Object", jsonObject.getString("places"));
//Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
}
Log.e("pla", json.toString());
} else {
//login_error.setText(json.getString("error_msg"));
}
} else {
Toast.makeText(getBaseContext(), "No data", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Please look over the link
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
an if possible made the changes in json, as there is no array braces "[" "]" in json and you need that to itrate in loop
json should be like that
{
"arrayKey": [
{
"tag": "home",
"success": 1,
"error": 0,
"uid": "4fc8f94f1a51c5.32653037",
"name": "Saleem",
"profile_photo": "http://example.info/android/profile_photos/profile1.jpg",
"places": {
"place_photo": "http://example.info/android/places_photos/place1.jpg",
"created_at": "2012-06-02 00:00:00",
"seeked": "0"
}
},
{
"tag": "home",
"success": 1,
"error": 0,
"uid": "4fc8f94f1a51c5.32653037",
"name": "Saleem",
"profile_photo": "http://example.info/android/profile_photos/profile1.jpg",
"places": {
"place_photo": "http://example.info/android/places_photos/place1.jpg",
"created_at": "2012-06-02 00:00:00",
"seeked": "0"
}
}
]
}
You could use the json libraries like the following:
import org.json.JSONArray;
import org.json.JSONObject;
which allows you to read json data into array like this:
JSONArray jsonArray = new JSONArray([your json data]);
Try this tutorial: http://www.vogella.com/articles/AndroidJSON/article.html
one other way I'll recommend is Use GSON library, It is easy end pain less. for well formatted Json
As your logcat states, you're trying to convert a JSONObject to a JSONArray:
org.json.JSONException: Value {"uid":"4fc8f94f1a51c5.32653037","places":{"place_photo":"http://example.info/android/places_photos/place1.jpg","created_at":"2012-06-02 00:00:00","seeked":"0","longitude":"24.943514","latitude":"60.167112"},"error":0,"success":1,"tag":"home","profile_photo":"http://example.info/android/profile_photos/profile1.jpg","name":"Zafar Saleem"} of type org.json.JSONObject cannot be converted to JSONArray
Try to debug the code - find out where the exception is thrown, and make a JSONObject there instead of a JSONArray.

Categories