Retrieving a single deep down array in JSON - java

So here is the JSON
{
"response": {
"data": {
"images": {
"image": [
{...
I want to access the image array. I was wondering if the following code was the best way to do it:
JSONObject jsonObjectResponse = new JSONObject(jsonString);
JSONObject jsonResponse = jsonObjectResponse.getJSONObject("response");
JSONObject jsonObjectData = new JSONObject(jsonResponse.toString());
JSONObject jsonData = jsonObjectData.getJSONObject("data");
JSONObject jsonObjectImages = new JSONObject(jsonData.toString());
JSONObject jsonImages = jsonObjectImages.getJSONObject("images");
JSONObject jsonObjectImage = new JSONObject(jsonImages.toString());
JSONArray jsonImageArray = jsonObjectImage.getJSONArray("image");
I feel like this requires a lot of time for a simple task. Does anyone have a more "engineered" solution?
Thanks a lot!

No, that's not the best way to do it. You keep converting from JSONObjects to Strings and then back to JSONObjects again. You should be able do:
JSONArray jsonImageArray = new JSONObject(jsonString)
.getJSONObject("response")
.getJSONObject("data")
.getJSONObject("images")
.getJSONArray("image");
Even if you just remove all of the toString calls, it becomes a lot more concise (but I would still favour the above example):
JSONObject jsonObjectResponse = new JSONObject(jsonString);
JSONObject jsonResponse = jsonObjectResponse.getJSONObject("response");
JSONObject jsonData = jsonResponse.getJSONObject("data");
JSONObject jsonImages = jsonData.getJSONObject("images");
JSONArray jsonImageArray = jsonImages.getJSONArray("image");

I think you can simply combine all these statements in the following way:
JSONObject jsonObjectResponse = new JSONObject(jsonString);
JSONArray jsonImageArray = jsonObjectResponse.getJsonObject("data")
.getJsonObject("images")
.getJsonArray("image");

Can you not chain the getJSONObject function?
JSONObject jsonObjectResponse = new JSONObject("jsonString");
JSONObject jsonImages = jsonObjectResponse.getJSONObject("response").getJSONObject("data")....

Try following:
JSONObject jsonObjectResponse = new JSONObject(jsonString);
JSONArray imageArray = jsonObjectResponse.getJSONObject("response")
.getJSONObject("data")
.getJSONObject("images")
.getJSONArray("image")
Hope it would work.

You can user chain calls:
String jsonString = "{\"response\":{\"data\":{\"images\":{\"image\":[]}}}}";
JSONObject json = new JSONObject(jsonString);
JSONArray image = json.getJSONObject("response")
.getJSONObject("data")
.getJSONObject("images")
.getJSONArray("image");
E.g. your image objects like {"title":"Some image","url":"http://..."}, so:
JSONObject firstImage = image.getJSONObject(0);
String url = firstImage.getString("url");
Or you can use GSON. Your classes:
class ServerAnswer {
private Response response;
// constructors, getters, setters
}
class Response {
private Data data;
// constructors, getters, setters
}
class Images {
#SerializedName("image")
private Image[] images;
// constructors, getters, setters
}
class Image {
private String url, title;
// constructors, getters, setters
}
And parse:
ServerAnswer answer = new Gson().fromJson(jsonString, ServerAnswer.class);
Image[] images = answer.getResponse().getData().getImages().getImagesArray();
Image firstImage = images[0];
String url = firstImage.getUrl();

In your case:
public class Images {
#SerializedName("image")
public ArrayList<String> image;
}
public class Data {
#SerializedName("images")
public Images images;
}
public class Response {
#SerializedName("data")
public Data data;
}
public class MyData {
#SerializedName("response")
public Response response;
}
then
MyData data = new Gson().fromJson(yourJsonString, MyData.class);
I think this is the best approach

You can try following code.
JSONArray jsonResponseArray = new JSONObject(strJson).getJSONObject("response").getJSONObject("data").getJSONObject("images").getJSONArray("image");
Hope this will help you.

Related

Android: How to get JSON object keys from this json:

This is the JSON array:
{
"server_response": [{
"Total": "135",
"Paid": "105",
"Rest": "30"
}]
}
So, how can i get the object names? I want to put them in separate TextView.
Thanks.
Put this out side everything. I mean outside onCreate() and all.
private <T> Iterable<T> iterate(final Iterator<T> i){
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return i;
}
};
}
For getting the names of objects :
try
{
JSONObject jsonObject = new JSONObject("{" +"\"server_response\": [{" +"\"Total\": \"135\"," +"\"Paid\": \"105\"," +"\"Rest\": \"30\"" +"}]"+"}";);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject object = jsonArray.getJSONObject(0);
for (String key : iterate(object.keys()))
{
// here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
Toast.makeText(HomeActivity.this, ""+key, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps :)
My suggestion:
Go to this website:
Json to pojo
Get your pojo classes and then use them in Android.
All you need to do is to use Gson.fromGson(params here).
One of your params is the class that you created using the online schema.
You can use jackson ObjectMapper to do this.
public class ServerResponse {
#JsonProperty("Total")
private String total;
#JsonProperty("Paid")
private String paid;
#JsonProperty("Rest")
private String rest;
//getters and setters
//toString()
}
//Now convert json into ServerResponse object
ObjectMapper mapper = new ObjectMapper();
TypeReference<ServerResponse> serverResponse = new TypeReference<ServerResponse>() { };
Object object = mapper.readValue(jsonString, serverResponse);
if (object instanceof ServerResponse) {
return (ServerResponse) object;
}
JSONObject jsonObject = new JSONObject("Your JSON");
int Total = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Total");
int Paid = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Paid");
int Rest = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Rest");

Gson deserialize not working properly

I have a jsonarray formatted like this:
String jsonArray = {"myList":[{"code":"01","price":"2,3", "date":"21/12/2014"},{"code":"02","price":"3,4", "date":"26/12/2014"}]}
Mylist class is:
public class MyList {
private String code;
private String price;
private String date;
//..getter and setter
}
My non working "deserializator" is the following:
ObjectMapper objectMapper = new ObjectMapper();
List<MyList> list = new ObjectMapper().readValue(jsonArray, new TypeReference<List<MyList>>() { });
catching the following exception:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
How can I solve that?
Thanks in advance!
Here's my own working solution using Gson:
String jsonArray = {"myList":[{"code":"01","price":"2,3", "date":"21/12/2014"},{"code":"02","price":"3,4", "date":"26/12/2014"}]}
Gson gson = new Gson();
JsonParser parser = new JsonParser();
List<MyList> list = new ArrayList<MyList>();
try {
JsonArray jArray = (JsonArray) parser.parse(jsonArray).getAsJsonObject().get("myList");
for (JsonElement jObj : jArray) {
MyList item = gson.fromJson( jObj , MyList.class);
list.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope it will be useful for other users!

Java Append object to JSON

I would like to append JSON object to existing JSON array to get data structure like this.
"results":[
{
"lat":"value",
"lon":"value"
},
{
"lat":"value",
"lon":"value"
}
]
I'm trying to do it using the code in example, but unfortunately whole object is overriden everytime.
Log.i(AppHelper.APP_LOG_NAMESPACE, "POSITIONS AVAILABLE " + jsonDataString);
AppHelper helper = new AppHelper(ctx);
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
//putv given values to the JSON
valuesObject.put("lat", lat.toString());
valuesObject.put("lon", lon.toString());
valuesObject.put("city", city);
valuesObject.put("street", street);
valuesObject.put("date", helper.getActualDateTime());
valuesObject.put("time", helper.getActualDateTime());
list.put(valuesObject);
//mainObject.put("values", list);
mainObject.accumulate("values", list);
saveJsonData(ctx, mainObject.toString(),"positions");
How it should be right?
Put and accumulate everytime rewrite all previous values, but i would like to append this object:
{
"lat":"value",
"lon":"value"
},
Into results parent.
BTW: I would like to do it without GSON.
Thanks for any help..
There isnt any problem with your code. It does append
String jsonDataString = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("lat", "newValue");
valuesObject.put("lon", "newValue");
valuesObject.put("city", "newValue");
valuesObject.put("street", "newValue");
valuesObject.put("date", "newValue");
valuesObject.put("time", "newValue");
list.put(valuesObject);
mainObject.accumulate("values", list);
System.out.println(mainObject);
This prints {"values":[[{"date":"newValue","city":"newValue","street":"newValue","lon":"newValue","time":"newValue","lat":"newValue"}]],"results":[{"lon":"value","lat":"value"},{"lon":"value","lat":"value"}]}.
Isnt this what you are expecting?
With gson you can do like
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class AddJson {
public static void main(String[] args) {
String json = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
Gson gson = new Gson();
JsonObject inputObj = gson.fromJson(json, JsonObject.class);
JsonObject newObject = new JsonObject() ;
newObject.addProperty("lat", "newValue");
newObject.addProperty("lon", "newValue");
inputObj.get("results").getAsJsonArray().add(newObject);
System.out.println(inputObj);
}
}
Simple Approach
String jsonData = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }]}";
System.out.println(jsonData);
try {
JSONArray result = new JSONObject(jsonData).getJSONArray("results");
result.getJSONObject(0).put("city","Singapore");
jsonData = "{\"results\":"+result.toString()+"}";
System.out.println(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
OutPut Before Appending
{"results":[{"lat":"value","lon":"value" }]}
OutPut After Appending
{"results":[{"lon":"value","lat":"value","city":"Singapore"}]}
If you want to add new value to an Object you can try the below as well
Before:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty"
}
code :
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(TheObjectToWhichYouWantToAddNewValue);
ObjectNode node = (ObjectNode) mapper.readTree(json);
node.putPOJO("new Key","new value")
after:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty",
"new Key": "new value"
}

Creating a JSON object

I am making a JSON request to server using Java. Here is the following parameters.
{method:'SearchBySearchConfiguration',params:[{{SearchCriteria:'%arriva',
IsAccountSearch:true,IsContactSearch:false,SearchByName:true,SearchByAddress:false
CRMTextValues:[], CRMCurrencyValues:[]}]}
I could do this way.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
How do I add the rest of params, in name-value pair to JSON object?
Thanks in advance!
One way I can think of is using the org.json library. I wrote a sample to build part of your request object:
public static void main(String[] args) throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("method", "SearchBySearchConfiguration");
JSONArray jsonArray = new JSONArray();
JSONObject innerRecord = new JSONObject();
innerRecord.put("SearchCriteria", "%arriva");
innerRecord.put("IsAccountSearch", true);
jsonArray.put(innerRecord);
jsonObject.put("params",jsonArray);
System.out.println("jsonObject :"+jsonObject);
}
The output is :
jsonObject :{"method":"SearchBySearchConfiguration","params":[{"IsAccountSearch":true,"SearchCriteria":"%arriva"}]}
Another technique would be to build Java objects that resemble your request structure. You can then convert it into json using Jackson library's ObjectMapper class.
In both cases once you get the json string, you can directly write it into the request body.
JSONObject json=new JSONObject();
json.put("method", "SearchBySearchConfiguration");
JSONArray paramsArr = new JSONArray();
JSONObject arrobj = new JSONOject();
arrobj.put("SearchCriteria","%arriva");
arrobj.put("IsAccountSearch","true");
arrobj.put("IsContactSearch","false");
arrobj.put("SearchByName","true");
arrobj.put("SearchByAddress","false");
arrobj.put("CRMTextValues",new JSONArray());
arrobj.put("CRMCurrencyValues",new JSONArray());
paramsArr.put(arrobj);
json.put("params",paramsArr);
The you can create JSONArray and put that array in JSONObject
Its Better to use gson for this.
First you need to create classs with following members :
public class TestClass{
private String method;
private ParamClass params;
}
public class ParamClass{
private String SearchCriteria;
private boolean IsAccountSearch;
private boolean IsContactSearch;
private boolean SearchByName;
private boolean SearchByAddress;
private String[] CRMTextValues;
private String[] CRMCurrencyValues;
}
Usage :
Serializing :
Gson gson = new Gson();
String jsonString = gson.toJson(testClassObject);
Deserializing :
Gson gson = new Gson();
TestClass testClassObject = gson.fromJson(jsonString , TestClass.class);
See this below example, where a JSONArray is returned and then how i am converting it in JSONObject form...
public JSONArray go() throws IOException, JSONException {
JSONArray json = readJsonFromUrl("http://www.xxxxxxxx.com/AppData.aspx");
return json;
}
JSONArray jarr;
for(int i=0 ; i<jarr.length() ; i++){
JSONObject jobj = jarr.getJSONObject(i);
String mainText = new String();
String provText = new String();
String couText = new String();
try{
mainText = jobj.getString("Overview");
System.out.println(mainText);
}catch(Exception ex){}
try{
JSONObject jProv = jobj.getJSONObject("Provider");
provText = jProv.getString("Name");
System.out.println(provText);
}catch(Exception ex){}
try{
JSONObject jCou = jobj.getJSONObject("Counterparty");
couText = jCou.getString("Value");
System.out.println(couText);
}catch(Exception ex){}
Jackson is a very efficient to do JSON Parsing
See this link:
http://jackson.codehaus.org/
Gson is provided by google which is also a good way to handle JSON.
To add params, JSONArray is used.
Inside params, we use JSONObject to add data such as SearchByAddress, IsAccountSearch ..etc.
Reference http://www.mkyong.com/java/json-simple-example-read-and-write-json/
package com.test.json;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("method", "SearchBySearchConfiguration");
JSONArray list = new JSONArray();
JSONObject innerObj = new JSONObject();
innerObj.put("SearchCriteria","%arriva" );
innerObj.put("IsAccountSearch",true);
innerObj.put("IsContactSearch",false);
innerObj.put("SearchByName",true);
innerObj.put("SearchByAddress",false);
innerObj.put("CRMTextValues",new JSONArray());
innerObj.put("CRMCurrencyValues",new JSONArray());
list.add(innerObj);
obj.put("params", list);
System.out.print(obj);
}
}

Java JsonObject array value to key

I'm new to java so this is a bit confusing
I want to get json formatted string
The result I want is
{ "user": [ "name", "lamis" ] }
What I'm currently doing is this :
JSONObject json = new JSONObject();
json.put("name", "Lamis");
System.out.println(json.toString());
And I'm getting this result
{"name":"Lamis"}
I tried this but it didnt work
json.put("user", json.put("name", "Lamis"));
Try this:
JSONObject json = new JSONObject();
json.put("user", new JSONArray(new Object[] { "name", "Lamis"} ));
System.out.println(json.toString());
However the "wrong" result you showed would be a more natural mapping of "there's a user with the name "lamis" than the "correct" result.
Why do you think the "correct" result is better?
Another way of doing it is to use a JSONArray for presenting a list
JSONArray arr = new JSONArray();
arr.put("name");
arr.put("lamis");
JSONObject json = new JSONObject();
json.put("user", arr);
System.out.println(json); //{ "user": [ "name", "lamis" ] }
Probably what you are after is different than what you think you need;
You should have a separate 'User' object to hold all properties like name, age etc etc.
And then that object should have a method giving you the Json representation of the object...
You can check the code below;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class User {
String name;
Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public JSONObject toJson() {
try {
JSONObject json = new JSONObject();
json.put("name", name);
json.put("age", age);
return json;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User lamis = new User("lamis", 23);
System.out.println(lamis.toJson());
}
}

Categories

Resources