Parse multiple items in JSON into an array - java

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();
}
}

Related

How to save data from textfields to json file?

how to save data from our textfields. For example i want to get this:
[
{
"Patient": {
"name": "John",
"surname": "Cena"
}
},
{
"Patient2": {
"name": "Roger",
"surname": "Federer"
}
}
]
And it was my try:
JSONObject obj = new JSONObject();
obj.put("imie", field1.getText());
obj.put("nazwisko", field2.getText());
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(obj.toJSONString());
Data.write(obj1.toJSONString());
} catch (IOException e1) {
e1.printStackTrace();
}
but i dont get "Patient2" and it overwriting my first patient if i press save button instead of add new one.
You should be using JSONArray to store several JSONObject instances:
// build object
JSONObject obj = new JSONObject();
obj.put("name", field1.getText());
obj.put("surname", field2.getText());
// build "patient"
JSONObject patient = new JSONObject();
patient.put("patient", obj);
// build another object
JSONObject obj1 = new JSONObject();
obj1.put("name", "Roger");
obj1.put("surname", "Federer");
// build another patient
JSONObject patient1 = new JSONObject();
patient1.put("patient1", obj1);
// create array and add both patients
JSONArray arr = new JSONArray();
arr.put(patient);
arr.put(patient1);
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(arr.toString(4)); // setting spaces for indent
} catch (IOException e1) {
e1.printStackTrace();
}
This code produces JSON:
[
{
"patient": {
"surname": "Doe",
"name": "John"
}
},
{
"patient1": {
"surname": "Federer",
"name": "Roger"
}
}
]

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;
}

How to access nested elements of JSON data in 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!!

Getting string from Json

I am new in json.My question is very simple.I have some array in my json file and also a string type of data.
Now I want to get the single text, name: anounce in my java class from json file.
How can i get this string from json ?
or any other way to get this ?
Json file
[{
"title": "KalerKantha | OfftechIT",
"image": "",
"link": "http://www.kalerkantho.com/"
}, {
"title": "Prothom Alo | OfftechIT",
"image": "",
"link": "http://www.prothom-alo.com/"
},
...
{
"anounce": "I need this this text"
}
]
Java Code
JsonArrayRequest movieReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setLink(obj.getString("link").toString());
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the Grid view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError){
hidePDialog();
Toast.makeText(getActivity(), " No Internet connection! \n Please check you connection", Toast.LENGTH_LONG).show();
}};
});
You simply make check the announce is present in the JSON or not
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
if(obj.has("anounce"))
{
String anounce= obj.getString("anounce");
}
else
{
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setLink(obj.getString("link").toString());
// adding movie to movies array
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
Use optString method. It would return the value if node exists and String.empty is node is not found.
From Documentation
public String optString (String name)
Returns the value mapped by name if it exists, coercing it if necessary, or the empty string if no such mapping exists.
Do this
try {
JSONObject obj = response.getJSONObject(i);
String announce = obj.optString("anounce");
Movie movie = new Movie();
movie.setTitle(obj.optString("title"));
movie.setThumbnailUrl(obj.optString("image"));
movie.setLink(obj.optString("link"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
Update: Using optString is much better, but if you don't want to use it then do this
try {
JSONObject obj = response.getJSONObject(i);
if(i == response.length() -1)
{
String announce = obj.getString("anounce");
}
else
{
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setLink(obj.getString("link").toString());
// adding movie to movies array
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
The Structure of your JSON is hard. But if you really want to get the string. Try this. Add this inside in for loop.
String data = (obj.getString("announce") != null) ? obj.getString("announce") : "";
// If you Movie has this annouce in your settler Getter if not try to add it.
Movie.setAnnounce(data);
Your code look like good but Are you add the request to queue
like:-
AppController.getInstance().addToRequestQueue(movieReq);
movieReq is JsonArrayRequest,
Please check it. and
String manounce=obj.getString("anounce");

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