Using JSON for nested level - java

I have the following json ,i am facing issue with creating jsonobject for this.Please let me know how to create a jsonobject with nested levels.
{
"menuConf": {
"class": "menu horizontal dropdown",
"caption": "",
"id": "mainMenu",
"container": "div",
"contClass": "navigation main left",
"helper": "span",
"items": [
{
"caption": "a",
"class": "orangesec",
"link": "#",
"id": "subMenu_1",
"helper": "span",
"items": [
{
"caption": "b",
"link": "#b"
},
{
"caption": "b",
"link": "#b"
},
{
"caption": "Blbogs",
"link": "#b"
},
{
"caption": "b",
"link": "#b"
}
]
}
]
}
}

What's wrong with the JSONObject(String) constructor? Just store your JSON text in a string and use it - it should handle nested objects just fine:
String json = "{...}";
try {
JSONObject o = new JSONObject(json);
// Print out the JSON text with a 4-space indentation
System.out.println(o.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}

Related

How to handle JsonObject to own Object

Now i take JsonObject from API like this:
Its XML object converted to JsonObject.
"Details": {
"row": [
{
"item": [
{
"name": "Account",
"value": 12521512
},
{
"name": "ACCNO",
"value": 4214
},
{
"name": "Number",
"value": 5436
}
]
},
"item": [
{
"name": "Account",
"value": 5789678
},
{
"name": "ACCNO",
"value": 6654
},
{
"name": "Number",
"value": 0675
}
]
},
But i need convert this object and send like this:
{
"Details": {
"row": [
{
"Account": 12521512,
"ACCNO": 4214,
"Number": 12412421
},
{
"Account": 5789678,
"ACCNO": 6654,
"Number": "0675"
}
]
}
}
I have rows more than 1000, i need faster way to handle.
How to handle, please help me
You could use the JSON-java library to parse your input and transform it to your desired format. Something like this works but you may need to adjust it to your needs:
JSONObject jsonObject = new JSONObject(json); // Load your json here
JSONObject result = new JSONObject("{\"Details\": {\"row\": []}}");
for (Object row : jsonObject.getJSONObject("Details").getJSONArray("row")) {
if (!(row instanceof JSONObject)) continue;
Map<Object, Object> values = new HashMap<>();
for (Object item : ((JSONObject) row).getJSONArray("item")) {
if (!(item instanceof JSONObject)) continue;
values.put(((JSONObject) item).get("name"), ((JSONObject) item).get("value"));
}
result.getJSONObject("Details").getJSONArray("row").put(values);
}
// Now result is in your format

Parsing nested JSON from a server

I am working on an android project that parses JSON from a file on a server and converting the data into java objects to display the data using text views.
The JSON file that I am parsing is based on a collection of books. Within each book entry is an author which has nested child elements for the last and first name of that author. Some entries can have multiple authors.
JSON file:
{
"bib": {
"book": [
{
"year": "1994",
"title": "TCP/IP Illustrated",
"author": {
"last": "Stevens",
"first": "W."
},
"publisher": "Addison-Wesley",
"price": "65.95"
},
{
"year": "1992",
"title": "Advanced Programming in the Unix environment",
"author": {
"last": "Stevens",
"first": "W."
},
"publisher": "Addison-Wesley",
"price": "65.95"
},
{
"year": "2000",
"title": "Data on the Web",
"author": [
{
"last": "Abiteboul",
"first": "Serge"
},
{
"last": "Buneman",
"first": "Peter"
},
{
"last": "Suciu",
"first": "Dan"
}
],
"publisher": "Morgan Kaufmann Puslishers",
"price": "39.95"
},
{
"year": "2012",
"title": "Professional Android 4 application development",
"author": {
"last": "Meier",
"first": "Reto"
},
"publisher": "ndianapolis : John Wiley and Sons",
"price": "33.47"
},
{
"year": "2017",
"title": "Java Programming for Beginners: Learn the fundamentals of programming with Java",
"author": {
"last": "Lassoff",
"first": "Mark"
},
"publisher": "Packt Publishing",
"price": "23.99"
},
{
"year": "2005",
"title": "Head First Java",
"author": [
{
"last": "Sierra",
"first": "Kathy"
},
{
"last": "Bates",
"first": "Bert"
},
],
"publisher": "MO'Reilly Media; 2 edition",
"price": "21.25"
},
{
"year": "2013",
"title": "XML for Dummies",
"author": {
"last": "Tittel",
"first": "Ed"
},
"publisher": "Wiley; 4th edition",
"price": "14.99"
},
{
"year": "2019",
"title": "Java XML and JSON: Document Processing for Java SE",
"author": {
"last": "Friesen",
"first": "Jeff"
},
"publisher": "Apress; 2nd ed. edition",
"price": "65.95"
},
{
"year": "2016",
"title": "Java Programming for Android Developers For Dummies (For Dummies (Computers))",
"author": {
"last": "Burd",
"first": "Barry A."
},
"publisher": "John Wiley and Sons; 2nd edition",
"price": "16.99"
}
]
}
}
JSON Parser:
private class parseJSON extends AsyncTask<Void, Void, List<Book>> {
private final String TAG = parseJSON.class.getSimpleName();
#Override
protected List<Book> doInBackground(Void... voids) {
Log.i(TAG, "Start Async to get books.");
ArrayList<Book> bookArray = new ArrayList<>(0);
String jsonUrl = getApplication().getString(R.string.json_feed);
HttpHandler httpHandler = new HttpHandler();
String jsonString = httpHandler.makeJsonServiceCall(jsonUrl);
Log.i(TAG, "Response from url: " + jsonString);
if( jsonString != null) {
try {
JSONObject root = new JSONObject(jsonString);
// Get JSON array node.
JSONArray books = root.getJSONObject("bib").getJSONArray("book");
// Looping through all the books.
for (int i = 0; i < books.length(); i++) {
JSONObject jsonBook = books.getJSONObject(i);
String year = jsonBook.getString("year");
String title = jsonBook.getString("title");
String author = jsonBook.getString("author");
String publisher = jsonBook.getString("publisher");
String price = "£" + jsonBook.getString("price");
final Book bookObject = new Book(year, title, author, publisher, price);
//Add the new books to our result array.
bookArray.add(bookObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return bookArray;
}
#Override
protected void onPostExecute( List<Book> books) {
super.onPostExecute(books);
Log.e(TAG, "Populate UI recycler view with json converted data.");
bookList.setValue(books);
}
}
What is the best way I can accomplish this?
Use Gson by google, in your gradle add:
implementation 'com.google.code.gson:gson:2.8.6'
and you get it like:
Book bookObject = new Gson().fromJson("json", Book.class);

How to Parsing nested JSON object in Android using Volley and POJO Class

{
"status": "1",
"message": "",
"result": {
"info": {
"tax": "0",
"discount": "0",
"minimum_spend": "300",
"delivery_charges": "0",
"last_updated": "1 week 15 hours ago"
},
"items": [
{
"name": "Eat At Home",
"menu_item_id": "12345",
"menu_cat_id": "4321",
"menu_cat_sku": "",
"nutritions": "",
"price": "1000",
"currency": "USD",
"desc": "Desription",
"category": "Promotion",
"image": "https://static.google.com/media/images/thumbs/343e8f41b18325a6058adc3773ed4d53.png",
"large_image": "https://static.google.com/media/images/343e8f41b18325a6058adc3773ed4d53.png",
"options": [],
"discount": "",
"weight": "",
"sku": "",
"status": "0",
"brand": []
},
{
"name": "Lunch Bundle",
"menu_item_id": "4321",
"menu_cat_id": "4321",
"menu_cat_sku": "",
"nutritions": "",
"price": "1500",
"currency": "USD",
"desc": "Description",
"category": "Promotion",
"image": "https://static.google.com/media/images/thumbs/62cdde279bbc3e45b8456f040d649b32.png",
"large_image": "https://static.google.com/media/images/62cdde279bbc3e45b8456f040d649b32.png",
"options": [],
"discount": "",
"weight": "",
"sku": "",
"status": "0",
"brand": []
},
My code
MenuResponse menuResponse = JsonParser.getInstance().parseMenuResponse(response);
public MenuResponse parseMenuResponse(String serverResponse) throws Exception {
MenuResponse response = null;
if (serverResponse != null) {
try {
response = gson.fromJson(serverResponse, MenuResponse.class);
} catch (JsonSyntaxException jse) {
throw new Exception(ERROR_MESSAGE);
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
try this.
JSONObject json = new JSONObject(response);
String status= json.getString("status");
JSONArray itemsArray= json.getJSONArray("items");
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject c = itemsArray.getJSONObject(i);
String name= c.getString("name");
//remaining data you will
}
Or else better you can use Retrofit.

How to parse a DiagnosticReport from a JSON and print the same JSON again?

I'm parsing a DiagnosticReport from a JSON file and It works fine, but when I try to print the same JSON file throught IParser encode function, the JSON is different to the original. I need to print the same JSON.
Original JSON (String json)
{
"resourceType": "DiagnosticReport",
"text": {
"status": "generated",
"div": "<div><p><b>Narrative A</b></p></div>"
},
"contained": [
{
"resourceType": "Patient",
"id": "1"
},
{
"resourceType": "Observation",
"id": "2",
"meta": {
"lastUpdated": "2017-03-22T22:00:28.089-05:00"
},
"text": {
"div": "<div><p><b>Narrative B</b></p></div>"
},
"comment": "a comment"
}
],
"status": "appended",
"code": {
"coding": [
{
"code": "Report01"
}
]
},
"subject": {
"reference": "#1"
},
"effectiveDateTime": "2017-03-22T22:00:28-05:00",
"issued": "2017-03-22T22:00:28.070-05:00",
"result": [
{
"reference": "#2"
}
]
}
First step is parse and the second step is encode and print
DiagnosticReport report = parser.parseResource(DiagnosticReport.class, json);
String encodeJSON = parser.encodeResourceToString(report);
System.out.println(encodeJSON);
And the result is different because the text tag in the Observation is not showed
{
"resourceType": "DiagnosticReport",
"text": {
"status": "generated",
"div": "<div xmlns=\"http://www.w3.org/1999/xhtml\"><p><b>Narrative A</b></p></div>"
},
"contained": [
{
"resourceType": "Patient",
"id": "1"
},
{
"resourceType": "Observation",
"id": "2",
"meta": {
"lastUpdated": "2017-03-22T22:00:28.089-05:00"
},
"comment": "a comment"
}
],
"status": "appended",
"code": {
"coding": [
{
"code": "Report01"
}
]
},
"subject": {
"reference": "#1"
},
"effectiveDateTime": "2017-03-22T22:00:28-05:00",
"issued": "2017-03-22T22:00:28.070-05:00",
"result": [
{
"reference": "#2"
}
]
}
I'm trying this because I have a DiagnosticReport generated by my software and I need print it completely in a JSON file.
Thanks for your help!!
It's not legal to have narrative in a contained resource, nor is it legal to have meta/lastUpdated. There are invariants that prohibit both. Ideally, the parsing software should have thrown an exception, but it's not overly surprising that the serializer has trouble serializing content that's not supposed to be there.
Look at dom-1 and dom-4 in dstu3 or dstu2

Parse Json String (Feed RSS file) in Android

How can I parse this piece of JSON code?
{
"direction": "ltr",
"id": "feed/http => //www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"continuation": "CLKM0OyU0rYC",
"self": [
{
" href": "https => //cloud.feedly.com/reader/3/stream/contents/feed%2Fhttp%3A%2F%2Fwww.theverge.com%2Frss%2Ffull.xml?n=20&unreadOnly=true"
}
],
"alternate": [
{
"href": "http://www.theverge.com/",
"type": "text/html"
}
],
"updated": 1367539068016,
"items": [
{
"id": "entryId",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "NBC's reviled sci-fi drama 'Heroes' may get a second lease on life as Xbox Live exclusive",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236096/nbc-heroes-may-get-a-second-lease-on-life-on-xbox-live",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "..."
},
"author": "Nathan Ingraham",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 15
},
{
"id": "entryId2",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "Senate rejects bipartisan gun control measure for background checks despite broad public support",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236136/senate-rejects-gun-control-amendment",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "...html content..."
},
"author": "T.C. Sottek",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 39
}
]
}
That is my solution but it doesn't work... what is my error? thanks
try{
//JSONArray elements = new JSONArray (response);
JSONObject json=new JSONObject(response);
JSONArray elements = json.getJSONArray("items");
Log.d(TAG, "Elemenenti numero" +elements.length());
// Getting Array of Contacts
// looping through All Contacts
for(int i = 0; i < elements.length(); i++){
JSONObject c = elements.getJSONObject(i);
// Storing each json item in variable
String identifier = c.getString("id");
String title = c.getString("title");
String link = c.getString("originId");
String data = c.getString("published");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date=new Date();
try {
date = format.parse(data);
System.out.println(date);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
String summary = summaryObj.getString("content");
JSONObject contentObj= c.getJSONObject("content");
String content = contentObj.getString("content");
JSONObject sourceObj= c.getJSONObject("origin");
String source = contentObj.getString("title");
if (summary.length()==0 && content.length()!=0) summary=content;
if (content.length()==0 && summary.length()!=0) content=summary;
String image=this.getFirstImage(content);
FeedItem toAdd=new FeedItem(identifier, title, link, date, null, summary, content, image, source);
toAdd.toString();
}
}catch (JSONException e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
There is no element called summary, you may try
if(c.has("summary")) {
JSONObject summaryObj= c.getJSONObject("summary");
}
if that doesn't work, please post your stacktrace, (logcat)
You don't have any tag named "originID". but you are trying to get String from it.
Similarly,you don't have tag "summary" also but you are trying to get JSONObject from it.

Categories