How to read a Json inside a Json in java? - java

I'm trying to get the data of this Json. As you can see the first element have a json inside of the json.
{
"client":{
"colour":"aabb11",
"height":200,
"xpos":0,
"packages":"com.samsung.incallUi",
"events":[
{
"action":"hide",
"class":"com.android.TextView",
"type":"2"
},
{
"colour":"00FF00",
"action":"show"
}
],
"width":600,
"ypos":20
},
"Map":" {red=blue, yellow=brown}",
"Country":"IT"
}
I get the json from:
Request request = new Request.Builder().url(INIT_URL).post(formBody).build();
Response response = client.newCall(request).execute();
I'm trying this, but don't work (give me an JsonSyntaxException):
...
JSONArray ja = new JSONArray(response.body().string());
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
String client = jo.getString("client");
String xpos = jo.getString("height");
String packages = jo.getString("xpos");
String events = jo.getString("packages");
...
}
...

The first element, "client" is an object not an array.
try
JSONObject ja= new JSONObject(response.body().string());

I recommend you to take a look into a JSON parser, such us Jackson or Gson.
Will do your life much easier.
//Jackson example
Client client = new ObjectMapper().readValue(jsonString, Client.class);
Just define your Client class with the fields in the JSON

I strongly recommend using Gson. If you can't get it right with gson, that means, your model is not correct. If you have a hard time creating the model for the json, you can auto generate the model instead of creating it your self.

Related

Forming custom JSON Object from the JSON response from elastic search

Am getting response from ElasticSearch, from that response i want to form another JSON with limited fields (like custom JSONObject).
Please find the response that am getting from elastic search.
{
"took":93,
"timed_out":false,
"_shards":{
"total":5,
"successful":5,
"skipped":0,
"failed":0
},
"hits":{
"total":1,
"max_score":1.0,
"hits":[
{
"_index":"attachment",
"_type":"doc",
"_id":"87740",
"_score":1.0,
"_source":{
"app_language":"ES",
"filetype":"PB",
"attachment":{
"date":"2006-05-03T15:17:53Z",
"content_type":"application/pdf",
"author":"JJamesN",
"language":"en",
"title":"Microsoft Word - te7000pb.doc",
"content":"European Electronic Controls Catalog ",
"content_length":12267
},
"ext":"pdf",
"fileContent":"JVBERi0xLjQNJeLjz9MNCjQ3ID"
}
}
]
}
}
Please find my java code that am trying to manipulate the response JSON to create a separate JSON with limited fields.
JSONObject jsonObject = new JSONObject(responseBody);
JSONObject hits = jsonObject.getJSONObject("hits");
JSONArray hitsArray=hits.getJSONArray("hits");
System.out.println("Hits---->"+hitsArray.toString());
From the response JSON, i just want to create a new JSON with the following Structure and fields.
{
"app_language":"ES",
"filetype":"PB",
"attachment.content" : "European Electronic Controls Catalog ",
"ext":"pdf",
}
Try this:
JSONObject jsonBody = new JSONObject();
jsonBody.put("app_language","value");
jsonBody.put("filetype","value");
jsonBody.put("attachment.content","value");
jsonBody.put("ext",ext);
//String requestBody = jsonBody.toString();
Just extract your values from response and use it any where you want.
Hope this helps.

Get the count of entries from a json file

I am trying to get json data from a fake api call and need to get the count of the items in it(so that in future I can call the actual restful service). I am not able to get the number of departments in the json. I am expecting the result as 4(int) here.
I am not able to get the string value(json) for the code below:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
Please find below the entire code:
String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);
JSONObject jsnobject = new JSONObject(json);
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
JSON Sample:
{
"Department":
[
{"SectionId":"1","SectionName":"Childrens Wear"},
{"SectionId":"2","SectionName":"Womens Wear"},
{"SectionId":"3","SectionName":"F&A"},
{"SectionId":"1","SectionName":"Mens Wear"}
]
}
I am new to java as well as api's.
Thanks,
You are either using incorrect key in code or you posted incorrect JSON example. You used locations as the key incode however there is no value against that key in sample JSON. You need to use Department as the key.
JSONArray jsonArray = jsnobject.getJSONArray("Department");

Converting Json to Pojo

I've recently decided to rewrite one of my older android applications and I can't figure out how to convert server response like this:
{
"response": "SUCCESS",
"data": {
"0": {
... fields ...
},
"1": {
... fields ...
},
... another objects
}
}
to regular java object (or in this case list of objects). I was previously using this method:
JSONObject response = new JSONObject(stringResponse);
JSONObject dataList = response.getJSONObject("data");
int i = 0;
while (true) {
dataList.getJSONObject(String.valueOf(i)); // here I get wanted object
i++;
}
to get relevant objects and then I can put them into List, but now I'm using Retrofit library and I'm not able to find any clean solution to parse such weird object using gson and retrofit.
Thanks for any help.
Edit: What I want:
Send request using retrofit like this:
#GET("/some params")
void restCall(... another params..., Callback<Response> callback);
and then have List of objects in Response object. What I don't know is how to declare Response object, so it can convert that weird response into normal List of objects.
You have many libraries around for this.. One i used was json-simple There you can just use:
JSONValue.parse(String);
look into gson too! i'm using it for all my projects, serializing and deserializing to pojos is remarkably simple and customizable (if needed, most things are fine out of the box)
gson
here is their first example:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
obj = gson.fromJson( json );
==> you get back the same object

Extracting JSON fields using java

I am trying to extract a person's details who liked a facebook page by passing the page id as parameter. I extracted the JSON content of that page and now from that I want to extract name and id of users.
How do I achieve that ?
Code:
JSONObject json = readurl("https://graph.facebook.com/pageid");
System.out.println(json.toString());
System.out.println("Page id is:"+json.get("id"));
JSON:
"likes":{
"data":[
{
"id":"*******",
"name":"vv"
},
{
"id":"********",
"name":"abc"
},
Code like this would do the trick.
JSONObject json = readurl("https://graph.facebook.com/pageid");
JSONArray dataJsonArray = json.getJSONArray("data");
for(int i=0; i<dataJsonArray.length; i++) {
JSONObject dataObj = dataJsonArray.get(i);
String id = dataObj.getString("id");
//Similarly you can extract for other fields.
}
Basically data is a JSONArray since it starts with [. So simply get would not work, you must use JSONArray.
Note: I haven't compiled this code, but I think I gave you idea to proceed. Also refer this link to get hold of basics of parsing JSON in java.
This snippet is not tested, but I'm pretty sure it works:
JSONArray data = json.getJSONArray("data");
for (int i=0; i < data.length(); i++) {
JSONObject o = data.getJSONObject(i);
sysout(o.getString("id");
sysout(o.getString("name");
}
I use google's Gson library from: https://code.google.com/p/google-gson/

How to access nested objects of a Json File

the string I have into "jsonString" is the content of this link: http://85.18.173.82/cineca/wp5/json/events.json
Now I want the value "Day" of the second "Event".
JSONObject o = new JSONObject(jsonString);
String day = o.getString("XXXXXXXXXX");
System.out.println(day);
What does I have to put as argument of o.getString?
Many thanks
JSONObject obj = new JSONObject(json);
JSONArray array = obj.getJSONArray("Events");
for(int i = 0 ; i < array.length() ; i++){
System.out.println(array.getJSONObject(i).getJSONObject("Event").getString("Day"));
}
In this way, you can access, thanks.
The way you're constructing your JSONObject is wrong. By using this constructor you're not reading the json from that URL, you're actually using that string as a json representation (which it is not).
If you want to first read the json from your URL you'll have to do an HTTP GET request and then construct a JSONObject out of the response.
For more info, take a look at JSONObject docs

Categories

Resources