JSON for constructing multilevel tree - java

I wanted to form JSON like this:
{
"Schedule": [
{
"id": "A",
"name": "Summary",
"ischild": "1",
"level1": [
{
"id": "A.1",
"name": "A.1",
"ischild": "1",
"level2": [
{
"id": "A.1.a",
"name": "Income Statement",
"ischild": "0"
},
{
"id": "A.1.b",
"name": "Balance Sheet",
"ischild": "0"
},
{
"id": "A.1.c",
"name": "A.1.c",
"ischild": "1",
"level3": [
{
"id": "A.1.c.1",
"name": "General RWA",
"ischild": "0"
},
{
"id": "A.1.c.2",
"name": "Standardized RWA",
"ischild": "0"
},
{
"id": "A.1.c.3",
"name": "Advanced RWA",
"ischild": "0"
}
]
}
]
}
]
}
]
}
But my code is giving below output:
{
"Schedule": [
{
"name": "Summary",
"ischild": "1",
"id": "A",
"N_LEVEL": "1"
},
{
"name": "A.1",
"ischild": "1",
"id": "A.1",
"N_LEVEL": "2"
},
{
"name": "Income Statement",
"ischild": "0",
"id": "A.1.a",
"N_LEVEL": "3"
},
{
"name": "Balance Sheet",
"ischild": "0",
"id": "A.1.b",
"N_LEVEL": "3"
},
{
"name": "A.1.c",
"ischild": "1",
"id": "A.1.c",
"N_LEVEL": "3"
},
{
"name": "General RWA",
"ischild": "0",
"id": "A.1.c.1",
"N_LEVEL": "4"
},
{
"name": "Standardized RWA",
"ischild": "0",
"id": "A.1.c.2",
"N_LEVEL": "4"
},
{
"name": "Advanced RWA",
"ischild": "0",
"id": "A.1.c.3",
"N_LEVEL": "4"
}
]
}
Here is my code:
public static String getJSONFromResultSet(ResultSet rs,String keyName)
{
System.out.println(" in getJSONFromResultSet method");
Map json = new HashMap();
List list = new ArrayList();
if(rs!=null)
{
try
{
ResultSetMetaData metaData = rs.getMetaData();
while(rs.next())
{
Map<String,Object> columnMap = new HashMap<String, Object>();
for(int columnIndex=1;columnIndex<=metaData.getColumnCount();columnIndex++)
{
if(rs.getString(metaData.getColumnName(columnIndex))!=null)
columnMap.put(metaData.getColumnLabel(columnIndex),rs.getString(metaData.getColumnName(columnIndex)));
else
columnMap.put(metaData.getColumnLabel(columnIndex), "");
}
list.add(columnMap);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
json.put(keyName, list);
}
return JSONValue.toJSONString(json);

I think your target structure could be better if it's names didn't change on every level. The level number is a value not a key. ischild makes no sense either, I think this is isNotALeaf, well that can be worked out, so leave that off too, so we have:
{
"id": "A",
"name": "Summary",
"level": "1",
"children": [
{
"id": "A.1",
"name": "A.1",
"level": "2",
"children": [
{
"id": "A.1.a",
"name": "Income Statement",
"level": "3"
},
{
"id": "A.1.b",
"name": "Balance Sheet",
"level": "3"
}
]
}
}
Then generate a self-referencing class with based on that for use in GSon:
package com.example;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
#Generated("org.jsonschema2pojo")
public class Child {
#Expose
private String id;
#Expose
private String name;
#Expose
private String level;
#Expose
private List<Child> children = new ArrayList<Child>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public List<Child_> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}

Related

How to split the list according to some object inside it

So, this is one method that takes user name and returns list of applications assigned to the user
public TransformedResponse getAppsList(String userName) throws BadRequestException, ConstraintViolationException
{​​​​​​​
...
else
{​​​​​​​
List<AppList> appsList = appDataRepository.findAll(checkUser);
return transformer.transform(appsList);
}​​​​​​​
}​​​​​​​
The found list (appsList) is :
[
{
"applicationId": 1,
"name": "Units",
"description": "Units description",
"category": "Main"
},
{
"applicationId": 2,
"name": "Devices",
"description": "Devices description",
"category": "Main"
},
{
"applicationId": 5,
"name": "Location",
"description": "Location description",
"category": "Others"
},
]
So this is one method in the transformer class that mentioned above:
public TransformedResponse transform(List<AppList> appsList)
{
TransformedResponse transformedResponse = new TransformedResponse();
transformedResponse.setData(appsList);
return transformedResponse;
}
So, the final result returned from transformer method:
{
"data": [
{
"applicationId": 1,
"name": "Units",
"description": "Units description",
"category": "Main"
},
{
"applicationId": 2,
"name": "Devices",
"description": "Devices description",
"category": "Main"
},
{
"applicationId": 5,
"name": "Location",
"description": "Location description",
"category": "Others"
},
]
}
So what I need is I want to split that appsList according to the category i.e Main and Others so the result should be :
{
"main": [
{
"applicationId": 1,
"name": "Units",
"description": "Units description",
"category": "Main"
},
{
"applicationId": 2,
"name": "Devices",
"description": "Devices description",
"category": "Main"
}
],
"others":[
{
"applicationId": 5,
"name": "Location",
"description": "Location description",
"category": "Others"
},
]
}
The Transformed response class:
public class TransformedResponse
{
public TransformedResponse()
{
super();
}
//private List<AppList> main;
//private List<AppList> others;
private List<AppList> data;
public List<AppList> getData()
{
return data;
}
public void setData(List<AppList> data)
{
this.data = data;
}
//public List<AppList> getMain()
//{
// return data;
//}
//public void setMain(List<AppList> main)
//{
// this.main = main;
//}
//public List<AppList> getOthers()
//{
// return others;
//}
//public void setOthers(List<AppList> others)
//{
// this.others = others;
//}
}
You can do it with groupingBy:
Map<String, AppList> map = appsList.stream().collect(Collectors.groupingBy(AppList::getCategory));

How to create RealmList<RealmList<Object>> in android

I am trying to get a RealmList of RealmList from server (JSON) into realm object. I am getting
error: Element type of RealmList must be a class implementing 'RealmModel' or one of the 'java.lang.String', 'byte[]', 'java.lang.Boolean', 'java.lang.Long', 'java.lang.Integer', 'java.lang.Short', 'java.lang.Byte', 'java.lang.Double', 'java.lang.Float', 'java.util.Date'.
{
"facilities": [
{
"facility_id": "1",
"name": "Property Type",
"options": [
{
"name": "Apartment",
"icon": "apartment",
"id": "1"
},
{
"name": "Condo",
"icon": "condo",
"id": "2"
},
{
"name": "Boat House",
"icon": "boat",
"id": "3"
},
{
"name": "Land",
"icon": "land",
"id": "4"
}
]
},
{
"facility_id": "2",
"name": "Number of Rooms",
"options": [
{
"name": "1 to 3 Rooms",
"icon": "rooms",
"id": "6"
},
{
"name": "No Rooms",
"icon": "no-room",
"id": "7"
}
]
},
{
"facility_id": "3",
"name": "Other facilities",
"options": [
{
"name": "Swimming Pool",
"icon": "swimming",
"id": "10"
},
{
"name": "Garden Area",
"icon": "garden",
"id": "11"
},
{
"name": "Garage",
"icon": "garage",
"id": "12"
}
]
}
],
"exclusions": [
[
{
"facility_id": "1",
"options_id": "4"
},
{
"facility_id": "2",
"options_id": "6"
}
],
[
{
"facility_id": "1",
"options_id": "3"
},
{
"facility_id": "3",
"options_id": "12"
}
],
[
{
"facility_id": "2",
"options_id": "7"
},
{
"facility_id": "3",
"options_id": "12"
}
]
]
}
try this solution
public class Exclusion extends RealmObject {
private int facilityId;
private int optionsId;
}
public class Exclusions extends RealmObject {
private RealmList<Exclusion> exclusions;
}
so now you can using RealmList<Exclusions> exclusionsRealmList as Realm list, legal
hope this helps
Gianthran's answer is close, but you should also set up relations.
public class Exclusion extends RealmObject {
#Index
private int facilityId;
#Index
private int optionsId;
private Facility facility;
private Option option;
}
And
public class Facility extends RealmObject {
#LinkingObjects("facility")
private final RealmResults<Exclusion> exclusions = null;
}
public class Option extends RealmObject {
#LinkingObjects("option")
private final RealmResults<Exclusion> exclusions = null;
}
I don't think the Exclusions object is necessary, I'd expect that the table is already a collection in a way.

Consuming a nested JSON array using Spring Boot and RestTemplate

I am attempting to consume an API in my Spring Boot application using an HTTP GET request which returns the below JSON. The issues I'm running into are that there is a JSON array contained inside the "playerentry" level with un-named/unheaded pairs of player and team info. For Spring, one would usually create a java class for each layer of the JSON and use the #JsonProperty() annotation to specify which part of the JSON to generate the Java Objects from. Without names for pairs contained inside the JSON array, and being unsure how to properly setup the java classes for the playerentry array and contained array pairs, I have been unable to use the RestTemplate and RestTemplateBuilder to consume this JSON. Any Help would be greatly appreciated.
{
"rosterplayers": {
"lastUpdatedOn": "2018-02-25 4:24:30 PM",
"playerentry": [
{
"player": {
"ID": "10138",
"LastName": "Abrines",
"FirstName": "Alex"
},
"team": {
"ID": "96",
"City": "Oklahoma City",
"Name": "Thunder",
"Abbreviation": "OKL"
}
},
{
"player": {
"ID": "9466",
"LastName": "Acy",
"FirstName": "Quincy"
},
"team": {
"ID": "84",
"City": "Brooklyn",
"Name": "Nets",
"Abbreviation": "BRO"
}
},
{
"player": {
"ID": "9390",
"LastName": "Adams",
"FirstName": "Steven"
},
"team": {
"ID": "96",
"City": "Oklahoma City",
"Name": "Thunder",
"Abbreviation": "OKL"
}
},
{
"player": {
"ID": "9375",
"LastName": "Afflalo",
"FirstName": "Arron"
},
"team": {
"ID": "103",
"City": "Sacramento",
"Name": "Kings",
"Abbreviation": "SAC"
}
},
{
"player": {
"ID": "9357",
"LastName": "Ajinca",
"FirstName": "Alexis"
},
"team": {
"ID": "110",
"City": "New Orleans",
"Name": "Pelicans",
"Abbreviation": "NOP"
}
},
{
"player": {
"ID": "9272",
"LastName": "Aldrich",
"FirstName": "Cole"
},
"team": {
"ID": "100",
"City": "Minnesota",
"Name": "Timberwolves",
"Abbreviation": "MIN"
}
},
{
"player": {
"ID": "9480",
"LastName": "Aldridge",
"FirstName": "LaMarcus"
},
"team": {
"ID": "106",
"City": "San Antonio",
"Name": "Spurs",
"Abbreviation": "SAS"
}
},
{
"player": {
"ID": "9454",
"LastName": "Alexander",
"FirstName": "Cliff"
},
"team": {
"ID": "95",
"City": "Orlando",
"Name": "Magic",
"Abbreviation": "ORL"
}
},
{
"player": {
"ID": "9299",
"LastName": "Allen",
"FirstName": "Tony"
},
"team": {
"ID": "107",
"City": "Memphis",
"Name": "Grizzlies",
"Abbreviation": "MEM"
}
}
]
}
}
This should work
class Roasterplayers {
String lastUpdatedOn;
List<PlayerEntry> playerentry;
}
class PlayerEntry {
Player player;
Team team;
}
class Player {
#JsonProperty("ID")
String id;
#JsonProperty("LastName")
String lastName;
#JsonProperty("FirstName")
String firstName;
}
class Team {
#JsonProperty("ID")
String id;
#JsonProperty("City")
String city;
#JsonProperty("Name")
String name;
#JsonProperty("Abbreviation")
String abbreviation;
}
Make sure you have Setters and Getters for each field

Exclude fields in json Using Jackson and Json-View

I am using json-view to create a dynamic json as per my need ,it is a great library ,I am using this library for a while now .
Recently I am facing a problem with my one of the Use cases, let me place my code first
User class
public class User {
private String name;
private String emailId;
private String mobileNo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
}
ScreenInfoPojo class
public class ScreenInfoPojo {
private Long id;
private String name;
private ScreenInfoPojo parentScreen;
private User createdBy;
private User lastUpdatedBy;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ScreenInfoPojo getParentScreen() {
return parentScreen;
}
public void setParentScreen(ScreenInfoPojo parentScreen) {
this.parentScreen = parentScreen;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
public User getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(User lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
Run code
public class TestMain {
public static void main(String[] args) throws JsonProcessingException {
User user=new User();
user.setName("ABC");
user.setEmailId("dev#abc123.com");
user.setMobileNo("123456789");
ScreenInfoPojo screen1=new ScreenInfoPojo();
screen1.setId(1l);
screen1.setName("Screen1");
screen1.setCreatedBy(user);
screen1.setLastUpdatedBy(user);
ScreenInfoPojo screen2=new ScreenInfoPojo();
screen2.setId(2l);
screen2.setName("Screen2");
screen2.setParentScreen(Screen1);
screen2.setCreatedBy(user);
screen2.setLastUpdatedBy(user);
ScreenInfoPojo screen3=new ScreenInfoPojo();
screen3.setId(3l);
screen3.setName("Screen3");
screen3.setParentScreen(Screen2);
screen3.setCreatedBy(user);
screen3.setLastUpdatedBy(user);
ScreenInfoPojo screen4=new ScreenInfoPojo();
screen4.setId(4l);
screen4.setName("Screen4");
screen4.setParentScreen(Screen3);
screen4.setCreatedBy(user);
screen4.setLastUpdatedBy(user);
List<ScreenInfoPojo> screens=new ArrayList<>();
screens.add(screen1);
screens.add(screen2);
screens.add(screen3);
screens.add(screen4);
ObjectMapper mapper = new ObjectMapper().registerModule(new JsonViewModule());
String json = mapper.writeValueAsString(JsonView.with(screens).onClass(ScreenInfoPojo.class, Match.match()
.exclude("*")
.include("id","name","createdBy.name","lastUpdatedBy.mobileNo","parentScreen.id")));
System.out.println("json"+json);
}
Result
[{
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 2,
"name": "Screen2",
"parentScreen": {
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 3,
"name": "Screen3",
"parentScreen": {
"id": 2,
"name": "Screen2",
"parentScreen": {
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 4,
"name": "Screen4",
"parentScreen": {
"id": 3,
"name": "Screen3",
"parentScreen": {
"id": 2,
"name": "Screen2",
"parentScreen": {
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {},
"lastUpdatedBy": {}
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}]
Expected Result
[{
"id": 1,
"name": "Screen1",
"parentScreen": null,
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 2,
"name": "Screen2",
"parentScreen": {
"id": 1
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 3,
"name": "Screen3",
"parentScreen": {
"id": 2
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}, {
"id": 4,
"name": "Screen4",
"parentScreen": {
"id": 3
},
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
}
}]
Problem
In my use case I have a class ScreenInfoPojo which refers to same class as parentScreen ,
I am trying to fetch specific field/fields of parent ( "parentScreen.id") instate I am getting all fields that I have defined on child/target Object ("id","name","createdBy.name","lastUpdatedBy.mobileNo","parentScreen.id") and parent response is again recursive ! One thing i observed that It is only happening in case of a class has its own reference , I placed User class reference as two different field createdBy and lastUpdatedBy and tried to fetch "name" and "mobileNo" respectively worked just fine.
Any suggestion to solve this problem will be really helpful !!!!
Thanks
Yes. Include clause does not work for reference to the same class.
That you can do?
Compile from source according to github instruction build from source
Update function JsonViewSerializer.JsonWriter.fieldAllowed
find:
if(match == null) {
match = this.currentMatch;
} else {
prefix = "";
}
and comment else clause
if(match == null) {
match = this.currentMatch;
} else {
//prefix = "";
}
You will get expected result. But. I do not know how it will affect another filters.
To have more control you could add property to JsonView class.
For example:
in JsonView add:
private boolean ignorePathIfClassRegistered = true;
public boolean isIgnorePathIfClassRegistered() {
return ignorePathIfClassRegistered;
}
public JsonView1<T> setIgnorePathIfClassRegistered(boolean ignorePathIfClassRegistered) {
this.ignorePathIfClassRegistered = ignorePathIfClassRegistered;
return this;
}
In JsonViewSerializer.JsonWriter.fieldAllowed function rewrite if clause to:
if(match == null) {
match = this.currentMatch;
} else {
if (result.isIgnorePathIfClassRegistered())
prefix = "";
}
And you could use it in your example like:
JsonView<List<ScreenInfoPojo>> viwevedObject = JsonView
.with(screens)
.onClass(ScreenInfoPojo.class,
Match.match()
.exclude("*")
.include("id","name")
.include("createdBy.name")
.include("lastUpdatedBy.mobileNo")
.include("parentScreen.id"))
.setIgnorePathIfClassRegistered(false);
ObjectMapper mapper = new ObjectMapper().registerModule(new JsonViewModule());
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String json = mapper.writeValueAsString(viwevedObject);
You can simply use jackson annotation #jsonignore on the field that you do not want in the json response.
I don't know whether you can or not use any annotations on your code . If so this is useless..
The most flexible way to serialize an object is to write a custom serializer.
If I understood your requirements correctly, the following serializer might work:
public class CustomScreenInfoSerializer extends JsonSerializer<ScreenInfoPojo> {
#Override
public void serialize(ScreenInfoPojo value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
gen.writeStartObject();
gen.writeNumberField("id", value.getId());
gen.writeStringField("name", value.getName());
gen.writeFieldName("createdBy");
gen.writeStartObject();
gen.writeStringField("name", value.getCreatedBy().getName());
gen.writeEndObject();
gen.writeFieldName("lastUpdatedBy");
gen.writeStartObject();
gen.writeStringField("mobileNo", value.getLastUpdatedBy().getMobileNo());
gen.writeEndObject();
if (value.getParentScreen() == null) {
gen.writeNullField("parentScreen");
}
else {
gen.writeFieldName("parentScreen");
gen.writeStartObject();
gen.writeNumberField("id", value.getParentScreen().getId());
gen.writeEndObject();
}
gen.writeEndObject();
}
}
Using
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(ScreenInfoPojo.class, new CustomScreenInfoSerializer());
mapper.registerModule(module);
String json = mapper.writeValueAsString(screens);
System.out.println(json);
produces
[
{
"id": 1,
"name": "Screen1",
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
},
"parentScreen": null
},
{
"id": 2,
"name": "Screen2",
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
},
"parentScreen": {
"id": 1
}
},
{
"id": 3,
"name": "Screen3",
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
},
"parentScreen": {
"id": 2
}
},
{
"id": 4,
"name": "Screen4",
"createdBy": {
"name": "ABC"
},
"lastUpdatedBy": {
"mobileNo": "123456789"
},
"parentScreen": {
"id": 3
}
}
]

Java Parse JSON Multidimensional Object element to String

I have JSONObject data with multiple object inside.
What i want to do is, make that json to simple hierarchy.
JSON Data
{
"Response": {
"type": "string",
"content": "0000"
},
"Data": {
"item": [
{
"firstname": {
"type": "string",
"content": "Bryan"
},
"lastname": {
"type": "string",
"content": "Adams"
},
"kids": {
"item": [
{
"name": {
"type": "string",
"content": "Tommy"
},
"age": {
"type": "string",
"content": "9"
}
},
{
"name": {
"type": "string",
"content": "Jane"
},
"age": {
"type": "string",
"content": "4"
}
}
]
}
},
{
"firstname": {
"type": "string",
"content": "Joey"
},
"lastname": {
"type": "string",
"content": "Cena"
},
"kids": {
"item": [
{
"name": {
"type": "string",
"content": "Maria"
},
"age": {
"type": "string",
"content": "7"
}
},
{
"name": {
"type": "string",
"content": "Dany"
},
"age": {
"type": "string",
"content": "3"
}
}
]
}
}
]
}
}
My code
package junk;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* #author Agung
*/
class Foo {
private static JSONObject objResponse = new JSONObject();
public static void main(String args[]) throws JSONException {
JSONObject jsonObj = new JSONObject("{\"Response\":{\"type\":\"string\",\"content\":\"0000\"},\"Data\":{\"item\":[{\"firstname\":{\"type\":\"string\",\"content\":\"Bryan\"},\"lastname\":{\"type\":\"string\",\"content\":\"Adams\"},\"kids\":{\"item\":[{\"name\":{\"type\":\"string\",\"content\":\"Tommy\"},\"age\":{\"type\":\"string\",\"content\":\"9\"}},{\"name\":{\"type\":\"string\",\"content\":\"Jane\"},\"age\":{\"type\":\"string\",\"content\":\"4\"}}]}},{\"firstname\":{\"type\":\"string\",\"content\":\"Joey\"},\"lastname\":{\"type\":\"string\",\"content\":\"Cena\"},\"kids\":{\"item\":[{\"name\":{\"type\":\"string\",\"content\":\"Maria\"},\"age\":{\"type\":\"string\",\"content\":\"7\"}},{\"name\":{\"type\":\"string\",\"content\":\"Dany\"},\"age\":{\"type\":\"string\",\"content\":\"3\"}}]}}]}}");
Foo.getResponseContent(jsonObj);
System.out.println(objResponse);
}
private static void getResponseContent(JSONObject jsonObj) throws JSONException {
Iterator<?> keys = jsonObj.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (jsonObj.get(key) instanceof JSONObject) {
JSONObject object = jsonObj.getJSONObject(key);
if (object.has("content")) {
String content = (String) object.get("content");
objResponse.put(key, content);
} else {
// if we get here, so the element have multiple node
objResponse.put(key, object);
getResponseContent(object);
}
}
}
}
}
with my code, i get this result :
{
"Response": "0000",
"Data": {
"item": [
{
"firstname": {
"type": "string",
"content": "Bryan"
},
"lastname": {
"type": "string",
"content": "Adams"
},
"kids": {
"item": [
{
"name": {
"type": "string",
"content": "Tommy"
},
"age": {
"type": "int",
"content": "9"
}
},
{
"name": {
"type": "string",
"content": "Jane"
},
"age": {
"type": "int",
"content": "4"
}
}
]
}
},
{
"firstname": {
"type": "string",
"content": "Joey"
},
"lastname": {
"type": "string",
"content": "Cena"
},
"kids": {
"item": [
{
"name": {
"type": "string",
"content": "Maria"
},
"age": {
"type": "int",
"content": "7"
}
},
{
"name": {
"type": "string",
"content": "Dany"
},
"age": {
"type": "int",
"content": "3"
}
}
]
}
}
]
}
}
only work for field with no multiple elements.
but what i wanted result is :
{
"Response": "0000",
"Data": {
"item": [
{
"firstname": "Bryan",
"lastname": "Adams",
"kids": {
"item": [
{
"name": "Tommy",
"age": 9
},
{
"name": "Jane",
"age": 4
}
]
}
},
{
"firstname": "Joey",
"lastname": "Cena",
"kids": {
"item": [
{
"name": "Maria",
"age": 7
},
{
"name": "Dany",
"age": 3
}
]
}
}
]
}
}
i have no idea how to remove objects from Data field.
Here is a program that creates the output in the format you want: like you, I have used recursion, the changes I made were:
I handled arrays
I created a new object to collect the data for a child that does not have the 'content' key.
Here is the code:
package test;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestMain {
public static void main(String args[]) throws Exception {
JSONObject objResponse = new JSONObject();
JSONObject jsonObj = new JSONObject(
"{\"Response\":{\"type\":\"string\",\"content\":\"0000\"},\"Data\":{\"item\":[{\"firstname\":{\"type\":\"string\",\"content\":\"Bryan\"},\"lastname\":{\"type\":\"string\",\"content\":\"Adams\"},\"kids\":{\"item\":[{\"name\":{\"type\":\"string\",\"content\":\"Tommy\"},\"age\":{\"type\":\"string\",\"content\":\"9\"}},{\"name\":{\"type\":\"string\",\"content\":\"Jane\"},\"age\":{\"type\":\"string\",\"content\":\"4\"}}]}},{\"firstname\":{\"type\":\"string\",\"content\":\"Joey\"},\"lastname\":{\"type\":\"string\",\"content\":\"Cena\"},\"kids\":{\"item\":[{\"name\":{\"type\":\"string\",\"content\":\"Maria\"},\"age\":{\"type\":\"string\",\"content\":\"7\"}},{\"name\":{\"type\":\"string\",\"content\":\"Dany\"},\"age\":{\"type\":\"string\",\"content\":\"3\"}}]}}]}}");
getResponseContent(jsonObj, objResponse);
System.out.println(objResponse.toString(2));
}
private static void getResponseContent(JSONObject jsonObj, JSONObject objResponse) throws JSONException {
Iterator<?> keys = jsonObj.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
JSONObject child = jsonObj.optJSONObject(key);
if (child != null) {
if (child.has("content")) {
objResponse.put(key, child.get("content"));
} else {
JSONObject responseChild = new JSONObject();
objResponse.put(key, responseChild);
getResponseContent(child, responseChild);
}
} else {
JSONArray children = jsonObj.optJSONArray(key);
if (children != null) {
JSONArray responseChildren = new JSONArray();
objResponse.put(key, responseChildren);
for (int i = 0; i < children.length(); i++) {
child = children.getJSONObject(i);
JSONObject responseChild = new JSONObject();
responseChildren.put(responseChild);
getResponseContent(child, responseChild);
}
}
}
}
}
}
Here is its output:
{
"Response": "0000",
"Data": {"item": [
{
"firstname": "Bryan",
"lastname": "Adams",
"kids": {"item": [
{
"name": "Tommy",
"age": "9"
},
{
"name": "Jane",
"age": "4"
}
]}
},
{
"firstname": "Joey",
"lastname": "Cena",
"kids": {"item": [
{
"name": "Maria",
"age": "7"
},
{
"name": "Dany",
"age": "3"
}
]}
}
]}
}

Categories