How to parse JSONObject with other JSONObjects inside it? - java

I have a question about getting jsonobjects out of a jsonobject.
This is what im getting back:
{
"data": {
"someid": {
"air_by_date": 0,
"cache": {
"banner": 1,
"poster": 1
},
"language": "en",
"network": "somenetwork",
"next_ep_airdate": "somedate",
"paused": 0,
"quality": "somequality",
"show_name": "somename",
"status": "Continuing",
"tvdbid": someid,
"tvrage_id": someid,
"tvrage_name": "Showname"
},
"someid": {
"air_by_date": 0,
"cache": {
"banner": 1,
"poster": 1
},
"language": "en",
"network": "somenetwork",
"next_ep_airdate": "",
"paused": 0,
"quality": "somequality",
"show_name": "somename",
"status": "Continuing",
"tvdbid": someid,
"tvrage_id": someid,
"tvrage_name": "somename"
},
But how am i supposed to create "ShowObjects" of them. I know how it works with JSONArrays but i have never done this kind of JSON before.
This is what i got untill now:
String json = download(url);
JSONObject result = new JSONObject(json);
JSONObject resultData = result.getJSONObject("data");

Copied from this answer:
Use the keys() iterator to iterate over all the properties, and call get() for each.
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}

Try using Jackson or Gson for these tasks.
With Jackson you would do something like this:
class Response() {
public String message;
public String result;
public Map<String, Object> data;
}
ObjectMapper mapper = new ObjectMapper()
Resonse respone = mapper.readValue(json, Response.class)
or use a custom deserializer to read those values out.

I will give you an example how to fetch the objects and vars in your "data" json:
lets say the second "someid" is : "123". We will fetch the second jsonObject now :
JSONObject secondJsonSomeId = resultData.getJsonObject("123");
Now we will fetch the "banner" ( int =1 ) of the jsonObject named "cache" located in our secondJsonSomeId :
int bannerInsecondJsonSomeId = secondJsonSomeId.getJsonObject("cache").getInt("banner");// bannerInsecondJsonSomeId == 1
the code is not compiled so there might be errors , ask if you have additional questions.

Related

How can I make an JSON in Java with org.json which does look like this example?

So, I tried something with java which looks like this, but the output does not look nice.
One of the code-examples I tried to make a json file with:
String name = "usericals.json";
JSONObject jsonObj = new JSONObject();
JSONArray scene = new JSONArray();
JSONArray element = new JSONArray();
jsonObj.put("scene", scene);
for (int i = 0; i < 1; i++) {
for (int ii = 0; ii < 1; ii++) {
element.put(write);
}
jsonObj.put("element", element);
}
scene.put(element);
try (PrintWriter writer = new PrintWriter("new.json", "UTF-8")) {
writer.write(jsonObj.toString(4));
} catch (Exception ex) {
System.out.println("exception " + ex);
}
I wanted to make a json file which looks like this but I cannot get it right. I am creating with my code above only arrays. Does anyone have an idea or suggestion?
The JSON File I want:
{
"scene": [
{
"id": 0,
"calendar_event": "urlaub",
"element": [
{
"anything": ""
},
{
"anything": ""
}
]
},
{
"id": 1,
"calendar_event": "urlauburlaub",
"element": [
{
"anything": ""
},
{
"anything": ""
}
]
},
{
"id": 2,
"calendar_event": "urlauburlauburlaub",
"element": [
{
"anything": ""
},
{
"device": "",
"anything": ""
}
]
},
{
"id": 3,
"calendar_event": "urlauburlauburlauburlaub",
"element": [
{
"anything": ""
},
{
"anything": ""
}
]
}
]
}
I suggest using library for that. Jackson or GSON would be a good choice.
Instead of manually creating json field by field you could create POJOs and then use Jackson's ObjectMapper. Example:
public class Car {
private String color;
private String type;
// standard getters setters
}
and then
ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);
Which will give
{"color":"yellow","type":"renault"}
Google has a lot of jackson tutorials!
Use JSONObject recursively. Try something like this (I add some extra indentation so it can be readed easily, but on real projects better use functions instead):
JSONObject json = new JSONObject();
JSONArray scene = new JSONArray();
JSONObject node = new JSONObject();
node.put("id", 0);
node.put("calendar_event", "urlaub");
JSONArray element = new JSONArray();
JSONObject enode = new JSONObject();
enode.put("anything", "");
element.add(enode);
//...
node.put("element", element);
scene.add(node);
json.put("scene", scene);
//...
Note like this you generate manually the JSONs, but there are other libraries that scan objects to generate jsons. Depending on your needs, it could be easer, but remember that making so you are going to overhead everything because you are going to need to hold in memory two copies of the same tree. Also dealing with hierarchical structures maybe a problem using plain java objects.

How to dynamically simplify json using java?

I have received a json string like so:
{
"data": [
{
"name": "Order",
"value": "2"
},
{
"name": "Address",
"value": "182"
},
{
"name": "DNS",
"value": "null"
},
{
"name": "SSID",
"value": "work"
},
{
"name": "Protocol",
"value": "0"
},
{
"name": "Key",
"value": ""
},
{
"name": "carrier",
"value": "undefined"
},
{
"name": "SSH",
"value": "1"
},
{
"name": "ntp_addr",
"value": ""
},
{
"name": "Name",
"value": ""
}
]
}
I used stringify on an html response and this is what I have to parse. As you can see, it is pretty redundant; I would much rather { "Order":"2" } than { "name":"Order","value":"2" } ... So an array of name-value pairs, instead of an array of objects.
Is there a way I can dynamically format this response so that it will be easier to parse?
What 'd like is to be able to say:
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject dataObject = data.getJSONObject(i);
String order = dataObject.getString("Order");
String address = dataObject.getString("Address");
// etc...
}
But the current format makes it almost impossible to parse. I'd need loops within loops.
I'd like to use com.google.gson library. And this response easy to parse with it:
private final JsonParser PARSER = new JsonParser();
public void parse(String jsonString) {
JsonObject dataObject = PARSER.parse(jsonString).getAsJsonObject();
JsonArray dataArray = dataObject.get("data").getAsJsonArray();
dataArray.iterator().forEachRemaining(element -> {
String name = element.getAsJsonObject().get("name").getAsString();
String value = element.getAsJsonObject().get("value").getAsString();
}
}
Or you can simply use TypeAdapters for json deserialization directly in the object.
Something like this should do the trick
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
JSONObject simplifiedDataObject = new JSONObject();
for (int i = 0; i < data.length(); i++) {
JSONObject dataField = data.getJSONObject(i);
simplifiedDataObject.put(dataField.getString("name"), dataField.get("value"));
}
You just iterate over each element in data, use the name field as the field on a new JSONObject and simply retrieve the value using the value key.

Android JSON parsing Json Array is [] Throws Null Pointer Exception while parsing, How to write in Proper way?

I have complex API that i parse and show in list view,I will be struggle to parse JSONArray.Here i will be in struggle following Json Array which is inside the posts json object "tags_name": ["Activities"],,some object it will come like "tags_name": [], this.Kindly review my question. My API and code is below. Presently i will implemented parsing code with model class. Once fix this issue i have to write list view coding please help me. May be my question formation is in silly way. please it look like means give some suggestion to frame question. Thanks in Advance.
MyAPI:
{
"status": true,
"nextpage": 0,
"count": 31,
"data": {
"postlist": [{
"posts": {},
"tags_name": ["Activities"],
"images_count": 3,
"images": [],
"post_user": [],
"is_encourage_user": true,
"encourage_feed_id": "1093"
},
{
"posts": {"id": "4647"},
"tags_name": [],
"images_count": 0,
"images": [],
"post_user": [],
"is_encourage_user": true,
"encourage_feed_id": "992"
}
]
},
"token": "wqeeqweqweqweqweqsfsdfsdf"
}
My Method for Parsing
private void parsingPostValues(String responseStatus) throws JSONException {
JSONObject responseObject = new JSONObject(responseStatus);
JSONObject datObject = responseObject.getJSONObject("data");
JSONArray postArr = new JSONArray(datObject.getString("postlist"));
for (int i = 0; i < postArr.length(); i++) {
JSONObject tempPostObject = postArr.getJSONObject(i);
JSONObject postObject = tempPostObject.getJSONObject("posts");
//setTag Array- this is the functional area i'm in bottle-neck.
try {
JSONArray tagNameArr = tempPostObject.getJSONArray("tags_name");
//ArrayList<Bean> tagListdata = new ArrayList<Bean>(tagNameArr.length());
if (tagNameArr.length()>0) {
for (int tagInfo = 0; tagInfo < tagNameArr.length(); tagInfo++) {
// listdata.add(tagNameArr.get(i).toString());
String tagme = "";
//Bean tagBean = new Bean();
//tagBean.setTagsArray((tagme.isEmpty() ? tagNameArr.get(tagInfo).toString() : "null")); //tagBean.setTagsArray(tagNameArr.get(tagInfo).toString());
//tagListdata.add(tagBean);
//beanAccess.setTagsArray(tagNameArr.get(tagInfo));
System.out.println("Tags Array:"+tagInfo+":"+tagNameArr.get(tagInfo));
}
//beanAccess.setTagsArray(tagListdata);
}
} catch (Exception e) {
e.printStackTrace();
}
}
replace this
JSONArray postArr = new JSONArray(datObject.getString("postlist"));
To
JSONArray postArr = datObject.getJSONArray("postlist");
Replace
String imgCount = tempPostObject.getString("images_count");
String is_encourage_user = tempPostObject.getString("is_encourage_user");
To
String imgCount = postObject.getString("images_count");
String is_encourage_user = postObject.getString("is_encourage_user");
It will work for you.

Accessing json string in java and creating hashmap Android

I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}

Convert JSON string to plain key value pair for logging

I have a JSON string, where consist of structure something like below, basically I have a chain of VO's and each VO will have list of VO's and Map of VO's as well.
sample:
"MessageHeader": {
"type": "new",
"id": 10,
"add_record": "true",
},
"MessageBody": {
"dob_required": false,
"dept_name": "Purchase",
"group": {
"main_group": "main group",
"sub_group": "sub group"
},
"family_info": {
"person1": {
"name": "HisName",
"gender": "male",
"age": "31",
"office_info_present": {
"office_name": "present office",
"office_address": "some address"
"some_other_vo":{
},
},
"office_info_previous": {
"office_name": "old office",
"office_address": "some address"
},
},
"person2": {
"name": "HerName",
"gender": "Female",
"age": "25",
}
},
"active":true
}
I want to print each and every attribute name and its value in key value pair. I don't want to print the VO name, rather just the end attributes (leaf level attributes)
like below string:
type=new id=10 add_record=true dob_required=false dept_name=purchase main_group="main group" sub_group="sub group" name=HisName gender=male age=31 .... name=HerName gender=Female age=25
How this can be done? I would prefer if it can be done using jackson. Otherwise also fine.
The easiest way is probably by using Jackson's Tree Model, traversing it. Something like:
JsonNode root = mapper.readValueAsTree(jsonInput);
Map<String,String> flat = new HashMap<String,String>();
traverse(root, flat);
public void traverse(JsonNode node, Map<String,String> result)
{
Iterator<Map.Entry<String,JsonNode>> it = node.fields();
while (it.hasNext()) {
Map.Entry<String,JsonNode> entry = it.next();
JsonNode n = entry.getValue();
if (n.isObject()) { // if JSON object, traverse recursively
traverse(n);
} else { // if not, just add as String
result.put(entry.getKey(), n.asText());
}
}
}
and you'll get a Map that you can print.
you can use this link for creating POGO class for your response. It will automatically generate class for your response.
Use google GSON library to parse your response.
Yes jackson can be used to parse. but its not straight forward.
There are few implementations similar to JAXB for XML. But I never tested them
Here is the rough code snippet.
JSONParser parser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("c:\\sample.json"));
String name = (String) jsonObject.get("name");
long age = (Long) jsonObject.get("age");
JSONArray msg = (JSONArray) jsonObject.get("messages");
System.out.println("Name:"+name);
System.out.println("Age:"+age);
System.out.println("Messages:");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}

Categories

Resources