Cannot cast from JsonElement to String while parsing from the JSON file - java

This is my first code for reading from a Json file but I keep getting an error message:
Can not cast from JasonElement to String
import java.io.FileReader;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Json
{
public static void main(String args[])
{
JsonParser parser = new JsonParser();
try
{
Object obj = parser.parse(new FileReader("C:\\Users\\dell\\eclipse-
workspace\\Assignment\\data.json"));
JsonObject jsonObject = (JsonObject) obj;
String name = (String) jsonObject.get("Name");
String author = (String) jsonObject.get("Author");
System.out.println("Name: " + name);
System.out.println("Author: " + author);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Excuse me for any silly mistakes.
I am still a beginner

By involking jsonObject.get("Name") you will get a JsonElement object and you can not cast to String. Maybe you can try:
jsonObject.get("Name").toString();

It depends on what you want.
If Name needs to be an actual JSON string value (as in, it must be { "Name": "str" } and not { "Name": [] }), then you should say jsonObject.get("Name").getAsString(). This causes an error if it isn't a string, which is desirable.
Otherwise, use jsonObject.get("Name").toString(), which returns a valid JSON value, as a String. E.g.
{ "Name": "a" } -> "a" (That's a string, 3 characters, two quote marks and an 'a')
{ "Name": false } -> false (That's a string, 5 chars, no quotes)

Related

How to check if a key name contains a number/special character for a nested json object without looping keys?

I'm trying to check whether a JSON object contains a number/special character in its name, and the JSON object is an array of objects and each object itself a nested JSON object and also some keys has an array of objects.
My scenario is if my JSON object contains a number in its key name, that's an error record so I have to remove or skip those kinds of JSON Object, how can I do.
In Talend, If I have JSON object like following it will throw an error that please provide well-formatted JSON
[{"abc":"abcd"},{"def":"abcd"},{"0":"saran"}]
Since it has 0 as key talend throws that error.
The following is my Actual JSON object
[
{"_id":"5dd71ec4ad611b6464f912eb","dimensions":{"0":"0[object Object]","container":1,"weigth":2,"height":253,"lenght":600,"width":400},"errorLocation":{"location":{"type":"Point","geometry":[]},"addressLines":[],"geocodeScore":0,"cleanScore":0},"execution":{"timer":{"timestamps":[]}}},
{"_id":"5ddb15c42fef196f91d279b1","dimensions":{"container":1,"weigth":2,"height":253,"lenght":600,"width":400},"errorLocation":{"location":{"type":"Point","geometry":[]},"addressLines":[],"geocodeScore":0,"cleanScore":0},"execution":{"timer":{"timestamps":[]}}}
]
SO I have tried with JAVA routine
Here is my Java routine code
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.*;
public class Carrefour_Data_Remove_Issue {
/**
* helloExample: not return value, only print "hello" + message.
*
*
* {talendTypes} String
*
* {Category} User Defined
*
* {param} string("world") input: The string need to be printed.
*
* {example} helloExemple("world") # hello world !.
* #throws JSONException
*/
public static String jsonInput(String message) throws JSONException {
//String escapedString = StringEscapeUtils.unescapeJava(message);
//message = message.trim();
JSONArray jsonArray = new JSONArray(message);
JSONArray jsonArrayOutput = new JSONArray();
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
//message = objectInArray.toString();
//System.out.println(isJSONValid(message));
JSONObject innerObject = objectInArray.getJSONObject("dimensions");
if(innerObject.has("0")==false)
{
jsonArrayOutput.put(objectInArray);
}
//System.out.println(innerObject);
}
//System.out.println(jsonArrayOutput);
message = jsonArrayOutput.toString();
return message;
}
public static boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
return false;
// edited, to include #Arthur's comment
// e.g. in case JSONArray is valid as well...
}
return true;
}
}
You can try something like
String jsonString = innerObject.toString();
boolean b = jsonString.matches(".*\"(.*\\W+.*)\":.*");
// if (b) smth
// else smth else
This regex matches strings with a special character or number which are preceeded by " and followed by ":

Retrieve the JSON Object

Below I have attached Java code, In that first i am retrieving the "images" result as "{"jpg":"JPEG file","gif":"GIF file","png":"PNG File"}"
using the resultant, trying to get the "jpg" node, not able to retrieve the data, instead i am getting error as java.lang.String cannot be cast to org.json.simple.JSONObject
I like to take the images and followed by jpg. not directly JPG value
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JSONDemo {
public static void main(String[] args) {
try{
String jsonfile="{ \"name\" : \"Raj\", \"Address\" : \"Chennai\", \"images\": { \"jpg\" : \"JPEG file\", \"png\" : \"PNG File\", \"gif\" : \"GIF file\" }}";
JSONObject jobject=new JSONObject();
JSONParser jparser=new JSONParser();
jobject = (JSONObject) jparser.parse(jsonfile);
jobject=(JSONObject) jobject.get("images");
System.out.println(jobject);
System.out.println(jobject.getClass().getName());
jobject=(JSONObject) jobject.get("jpg");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
Your error here is that "jpg" is not a JSONObject, but a key with the associated value "JPEG file" which is a simple String. That is why you're getting such error.
In ordre to retrieve the value associated to the key jpg, read the below code. I added some comments to help you understand each steps, but feel free to ask for more details.
String jsonfile="{ \"name\" : \"Raj\", \"Address\" : \"Chennai\", \"images\": { \"jpg\" : \"JPEG file\", \"png\" : \"PNG File\", \"gif\" : \"GIF file\" }}";
JSONObject jobject = new JSONObject();
JSONParser jparser = new JSONParser();
//Convert your string jsonfile into a JSONObject
try {
jobject = (JSONObject) jparser.parse(jsonfile);
} catch (ParseException ex) {
Logger.getLogger(Josimarleewords.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(jobject.toString());
//{"Address":"Chennai","name":"Raj","images":{"jpg":"JPEG file","png":"PNG File","gif":"GIF file"}}
//Get the node image, and convert it into a JSONObject
//You're able to do so, because the value associated to "images"
//is in json format.
jobject=(JSONObject) jobject.get("images");
System.out.println(jobject.toString());
//{"jpg":"JPEG file","png":"PNG File","gif":"GIF file"}
//Retrieves the value associated to the key jpg.
//The value here is not in json format, it is a simple string
String jpg = (String)jobject.get("jpg");
System.out.println(jpg.toString());
//JPEG file

How to extract each element (Bookmark) from a json file as an item using Java?

I’m trying to extract my bookmarks from Chrome’s bookmarks file, which is stored in the json format. I have a large number of bookmarks. This sample file below is a new Google profile to make a small number of elements for a workable file.
So far I have constructed a java program to iterate through the file and extract the keys. My problem is that some of the keys are arrays and have multiple keys in the item. At present I’m trying to figure out how to get those individual elements.
Each of the bookmarks are identified with a unique ID. So if I can get the key by ID, then associate each of the other elements of the key with that unique ID, I believe I’ll have each of the bookmarks.
My final objective is to put the bookmarks into a database so that I can have a better way of organizing them such as, searching, finding duplicates, categorizing and adding comments, etc.
My java program is the below. Also below the java program is the output after running it on the attached Chrome bookmark file.
Bookmarks file:
Bookmarks.json:
{
"checksum": "d27be6b28b9a8879c2cb9ba6fc90df21",
"roots": {
"bookmark_bar": {
"children": [ {
"date_added": "13081990058553125",
"id": "7",
"meta_info": {
"stars.id": "ssc_c257c6390425956c",
"stars.version": "sync.server.Chrome45"
},
"name": "Google",
"sync_transaction_version": "1",
"type": "url",
"url": "https://www.google.com/"
}, {
"date_added": "13078166246742000",
"id": "9",
"meta_info": {
"stars.flags": "5",
"stars.id": "ssc_7150b291c6b52a37",
"stars.pageData": "Ig5keGVLcUJvcW5kTjZSTQ==",
"stars.type": "2"
},
"name": "Apollo III Communications",
"sync_transaction_version": "1",
"type": "url",
"url": "http://www.apollo3.com/"
} ],
"date_added": "13113606994595146",
"date_modified": "13083379523340359",
"id": "1",
"name": "Bookmarks bar",
"type": "folder"
},
"other": {
"children": [ ],
"date_added": "13113606994595154",
"date_modified": "0",
"id": "2",
"name": "Other bookmarks",
"type": "folder"
},
"sync_transaction_version": "5",
"synced": {
"children": [ ],
"date_added": "13113606994595157",
"date_modified": "0",
"id": "3",
"name": "Mobile bookmarks",
"type": "folder"
}
},
"version": 1
}
Java Program to iterate through and extract the bookmarks:
getChromeBookmarks.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class getChromeBookmarks {
#SuppressWarnings("resource")
public static void main(String[] args) {
String infile = "/home/users/l/j/ljames/work/json/Bookmarks.json";
String content = null;
try {
content = new Scanner(new File(infile)).useDelimiter("\\Z").next();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(content);
printJsonObject(json);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void printJsonObject(JSONObject jsonObj) {
for (Object key : jsonObj.keySet()) {
// based on the key types
String keyStr = (String) key;
Object keyvalue = jsonObj.get(keyStr);
// Print key and value
System.out.println("key: " + keyStr + " value: " + keyvalue);
// expand(keyvalue);
// for nested objects iteration if required
if (keyvalue instanceof JSONObject)
printJsonObject((JSONObject) keyvalue);
}
}
}
Output of the java/jason program:
key: checksum value: d27be6b28b9a8879c2cb9ba6fc90df21
key: roots value: {"other":{"date_added":"13113606994595154","date_modified":"0","children":[],"name":"Other bookmarks","id":"2","type":"folder"},"synced":{"date_added":"13113606994595157","date_modified":"0","children":[],"name":"Mobile bookmarks","id":"3","type":"folder"},"bookmark_bar":{"date_added":"13113606994595146","date_modified":"13083379523340359","children":[{"date_added":"13081990058553125","meta_info":{"stars.id":"ssc_c257c6390425956c","stars.version":"sync.server.Chrome45"},"name":"Google","id":"7","type":"url","url":"https:\/\/www.google.com\/","sync_transaction_version":"1"},{"date_added":"13078166246742000","meta_info":{"stars.pageData":"Ig5keGVLcUJvcW5kTjZSTQ==","stars.id":"ssc_7150b291c6b52a37","stars.type":"2","stars.flags":"5"},"name":"Apollo III Communications","id":"9","type":"url","url":"http:\/\/www.apollo3.com\/","sync_transaction_version":"1"}],"name":"Bookmarks bar","id":"1","type":"folder"},"sync_transaction_version":"5"}
key: other value: {"date_added":"13113606994595154","date_modified":"0","children":[],"name":"Other bookmarks","id":"2","type":"folder"}
key: date_added value: 13113606994595154
key: date_modified value: 0
key: children value: []
key: name value: Other bookmarks
key: id value: 2
key: type value: folder
key: synced value: {"date_added":"13113606994595157","date_modified":"0","children":[],"name":"Mobile bookmarks","id":"3","type":"folder"}
key: date_added value: 13113606994595157
key: date_modified value: 0
key: children value: []
key: name value: Mobile bookmarks
key: id value: 3
key: type value: folder
key: bookmark_bar value: {"date_added":"13113606994595146","date_modified":"13083379523340359","children":[{"date_added":"13081990058553125","meta_info":{"stars.id":"ssc_c257c6390425956c","stars.version":"sync.server.Chrome45"},"name":"Google","id":"7","type":"url","url":"https:\/\/www.google.com\/","sync_transaction_version":"1"},{"date_added":"13078166246742000","meta_info":{"stars.pageData":"Ig5keGVLcUJvcW5kTjZSTQ==","stars.id":"ssc_7150b291c6b52a37","stars.type":"2","stars.flags":"5"},"name":"Apollo III Communications","id":"9","type":"url","url":"http:\/\/www.apollo3.com\/","sync_transaction_version":"1"}],"name":"Bookmarks bar","id":"1","type":"folder"}
key: date_added value: 13113606994595146
key: date_modified value: 13083379523340359
key: children value: [{"date_added":"13081990058553125","meta_info":{"stars.id":"ssc_c257c6390425956c","stars.version":"sync.server.Chrome45"},"name":"Google","id":"7","type":"url","url":"https:\/\/www.google.com\/","sync_transaction_version":"1"},{"date_added":"13078166246742000","meta_info":{"stars.pageData":"Ig5keGVLcUJvcW5kTjZSTQ==","stars.id":"ssc_7150b291c6b52a37","stars.type":"2","stars.flags":"5"},"name":"Apollo III Communications","id":"9","type":"url","url":"http:\/\/www.apollo3.com\/","sync_transaction_version":"1"}]
key: name value: Bookmarks bar
key: id value: 1
key: type value: folder
key: sync_transaction_version value: 5
key: version value: 1
Update: This is an example of what I am trying to do, code from:
https://stackoverflow.com/a/40887240/1204365
import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Bookmark {
private static String jsonFile = "/home/users/l/j/ljames/.config/google-chrome/Default/Bookmarks";
public static void main(String[] args) {
// TODO Auto-generated method stub
FileReader reader = new FileReader(jsonFile); // access the file
JSONObject jsonObject = (JSONObject) new JSONParser().parse(reader);
String checksum = jsonObject.optString("checksum");
// get root object
JSONObject root = jsonObject.getJSONObject("roots");
// get root bookmarks object from root
JSONObject bookmarks = root.getJSONObject("bookmark_bar");
// get root children array from bookmarks
JSONArray childrens = bookmarks.getJSONArray("children");
JSONObject temp;
for (int i = 0; i < childrens.size(); i++) {
// get object using index from childrens array
temp = childrens.getJSONObject(i);
// get url
String url = temp.optString("url");
}
}
}
The output/errors are:
check: b8b257094128d165d7ccc70d0498cc87
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
at javaTools.JsonParser.main(JsonParser.java:27)
There are six red marks in Eclipse. They are on the lines below. The suggested fix for each line is the same as the first... (highlight in bold text):
Line 19: String checksum = jsonObject.optString("checksum");
Error: Suggesting:
Change to 'toJSONString(..)'
Add cast to 'temp'
Rename in file (Ctrl+2 R)
This same suggestion is repleated for the other five red error marks.
Line 22: JSONObject root = jsonObject.getJSONObject("roots");
Line 25: JSONObject bookmarks = root.getJSONObject("bookmark_bar");
Line 28: JSONArray childrens = bookmarks.getJSONArray("children");
Line 33: temp = childrens.getJSONObject(i);
Line 36: String url = temp.optString("url");
The parsing all URL links required nested traversing mean there can be nested arrays inside arrays and object.
Approach :
1.) we will fetch all the keys inside root element and traverse them so first parse the object
try {
jsonObject = (JSONObject) new JSONParser().parse(reader);
} catch (IOException | ParseException e) {
e.printStackTrace();
}
Then fetch all the keys from required parent element i.e. root and traverse them using foreachloop.
JSONObject root = (JSONObject) jsonObject.get("roots");
// fetch all keys using keyset
Set<String> set = root.keySet();
// traverse all keys using foreach loop
for (String string : set) {
2.) While traversing we simply try to convert key as jsonobject and if key simply is a string inside our json file then exception will be raised string cannot be converted to JSONObject but will be catched so don't worry
for (String string : set) {
try {
obj = (JSONObject) root.get(string);
} catch (ClassCastException e) {
// no need to do anything here
}
}
3.) If it's a JSONObject then we simply try to find the children array which actually contains our urls links
if (obj.containsKey("children")) {
try {
childrens = (JSONArray) obj.get("children");
// call to recursive function to find nested children array
//and print url
printUrls(childrens);
} catch (Exception e) {
// try-catch to handle any unexpected case
}
}
4.) Now the nested array part , since any children can contain nested children arrays so i applied the concept of recursion to find and fetch content of nested arrays
public static void printUrls(JSONArray childrens) {
JSONObject temp = null;
for (int i = 0; i < childrens.size(); i++) {
// get object using index from children array
temp = (JSONObject) childrens.get(i);
// check if it contains any nested children array key
// if yes then , fetch the nested children array and call this funtion
// again to print it's content
if (temp.containsKey("children")) {
printUrls((JSONArray) temp.get("children"));
}
// fetch and print the url , most wanted guy here
String url = (String) temp.get("url");
if (url != null) {
// display the url using print
System.out.println(url);
// count is a variable which will be incremented when any url found
// and total of found urls , will be displayed at the end of parsing
count++;
}
}
}
Org.JSON jar link : click download jar option in the link and/or add it as a dependency jar in your project
Code
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
// parsing code using json.simple
public class Test2 {
// path to your file
private static String jsonFile = "C:\\bookmarks.json";
static int count = 0;
public static void main(String[] args) {
// a file reader class to access the file using string file path
FileReader reader = null;
try {
reader = new FileReader(jsonFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // access the file
JSONObject jsonObject = null;
try {
jsonObject = (JSONObject) new JSONParser().parse(reader);
} catch (IOException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String checksum = (String) jsonObject.get("checksum");
JSONObject root = (JSONObject) jsonObject.get("roots");
Set<String> set = root.keySet();
JSONArray childrens = null;
JSONObject obj = null;
for (String string : set) {
try {
obj = (JSONObject) root.get(string);
} catch (ClassCastException e) {
}
if (obj.containsKey("children")) {
try {
childrens = (JSONArray) obj.get("children");
printUrls(childrens);
} catch (Exception e) {
}
}
}
// display , how many urls we have found
System.out.println("count is " + count);
}
public static void printUrls(JSONArray childrens) {
JSONObject temp = null;
for (int i = 0; i < childrens.size(); i++) {
// get object using index from childrens array
temp = (JSONObject) childrens.get(i);
if (temp.containsKey("children")) {
printUrls((JSONArray) temp.get("children"));
}
// get url
String url = (String) temp.get("url");
if (url != null) {
System.out.println(url);
count++;
}
}
}
}
Output : The link provided by OP has 2521 urls so can't post all but count value should be enough
...
http://www.team-cymru.org/bogon-reference-http.html
http://www.team-cymru.org/bogon-reference-bgp.html
http://www.team-cymru.org/Services/Bogons/fullbogons-ipv4.txt
http://tecadmin.net/enable-logging-in-iptables-on-linux/#
https://www.youtube.com/watch?v=geglU1AdmJs&t=480s
count is 2521
If you could extract the entire json as one string, you could use JSONObject which would look like this:
JSONObject job = new JSONObject(response);
Then you can extract elements or even elements in arrays like this:
job.getString("name");
JSONArray my_list = job.getJSONArray("Children").getJSONObject(0).getString("date_added");
This is what I use to sort through the json
InputStream instream = entity.getContent()
String response = readInputStream(instream);
static private String readInputStream(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"));
String tmp;
StringBuilder sb = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
sb.append(tmp).append("\n");
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
sb.setLength(sb.length() - 1);
}
reader.close();
return sb.toString();
}

Java - Parsing JSON Response - Content is either String or JSONObject

I am facing a typical scenario while parsing JSON Response for one of the Service calls.
The content for one of the attributes (from below example, consider "name" as a attribute) coming as either String or JSONObject.
How to handle these kind of scenarios through code. Also, please consider that json content need not be consistent with same set of attributes.
Example:
String Response
{"name":"Adam"}
JSON Response
{"name":{"FirstName":"Adam", "MiddleName":"Don"} }
OR
{"name":{"FirstName":"Adam", "LastName":"Don"} }
OR
{"name":{"MiddleName":"Adam", "LastName":"Don"} }
You can ask the root JSONObject with the method optJSONObject(name) to return a JSONObject for the given name if it exists and is an JsonObject. Otherwise you can also test with optString(name) for a String.
So something like:
JSONObject root = new JSONObject(... data from server ... );
JSONObject obj = root.optJSONObject("name");
if (obj != null) {
// Do something with the object
} else {
String name = root.getString("name");
// Do something with the string
}
Parse your response JSON as a JSONObject, then get another JSONObject for the "name" key, if it throws a JSONException then your object is probably a String in with case you can call get String for the "name" key in your catch block.
String name = "";
JSONObject serverJSON = new JSONObject(YOUR_JSON_RESPONSE_STRING_FROM_SERVER);
try {
JSONObject nameObject = serverJSON.getJSONObject("name");
if (nameObject.has("first_name")) {
name = nameObject.getString("first_name") + " ";
}
if (nameObject.has("middle_name")) {
name += nameObject.getString("middle_name") + " ";
}
if (nameObject.has("last_name")) {
name += nameObject.getString("last_name");
}
name = name.trim();
} catch (JSONException e) {
// Probably a String, try again...
try {
name = serverJSON.getString("name");
catch (JSONException e) {
// Not a String or a JSONObject... figure out what's wrong...
e.printStackTrace();
}
}
I would really recommend though, that if you have any control of the server that you make sure that the name key choose one type and sticks to it; a JSONObject... You would be able to use the has(String key) member function in if statements to properly find all of your data without knowing what existed at runtime...
EDIT: Thought of a different idea... Parse the String to the first colon and see if the next non-whitespace character is a quotation mark, if it is, then your key belongs to a String, if it is a curly brace then it's a JSONObject. (If neither, then you have an error, because you aren't expecting an array or number or null or anything else...)
boolean jsonIsString = true;
String searchString = json.substring(json.indexOf(":")).trim();
if ("{".equals(searchString.charAt(0)) {
jsonIsString = false;
}
Tonity's solution is good. You can also use this solution.
In my solution, there will be no any Exception fired until JSON is wrong. What I am doing is following.
Search for number of ":" in string.
If it returns 1, then we sure that there is "name" value.
Otherwise, we need to check, whether there is "FirstName","MiddleName" or "LastName" exist in string or not.
Just go through this snippet and you will find solution for your problem.
// String str = "{\"name\":\"chintan\"}";
String str = "{\"name\":{\"FirstName\":\"Chintan\",\"LastName\":\"Rathod\"}}";
try {
//we will check how many ":" are there in string, if it is one, then
// we are going to get "name" field.
if ((str.split(":").length - 1) == 1)
{
Log.d("Home", "1");
JSONObject json = new JSONObject(str);
Log.d("Home", "Name : " + json.get("name"));
}
else
{
Log.d("Home", "more then 2");
JSONObject jName = new JSONObject(str);
JSONObject jTemp = jName.getJSONObject("name");
if (jTemp.toString().contains("FirstName"))
Log.d("Home", "FirstName :" + jTemp.getString("FirstName"));
if (jTemp.toString().contains("MiddleName"))
Log.d("Home","MiddleName :" +jTemp.getString("MiddleName"));
if (jTemp.toString().contains("LastName"))
Log.d("Home", "LastName :" + jTemp.getString("LastName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Output
08-06 11:52:34.060: D/Home(1439): more then 2
08-06 11:52:34.060: D/Home(1439): FirstName :Chintan
08-06 11:52:34.070: D/Home(1439): LastName :Rathod
I faced a problem like this as well. I didn't want to parse the JSON manually. Do this if firstName exists otherwise do that. I didn't want to mess up my structure because I only define java object and my client handles the parsing. So, I came up with following:
#Getter
#Setter
#ToString
class Response {
private Name name;
#Getter
#Setter
#NoArgsConstructor
#ToString
public static class Name {
private String name;
private String firstName;
private String middleName;
private String lastName;
public Name(String name) {
this.name = name;
}
}
}
Then, parse the json;
ObjectMapper objectMapper = new ObjectMapper();
Response response = objectMapper.readValue(json, Response.class);
Now, string response and JSON response can be parsed with the same class.

Parse Json In Java How to read Inner Value

Very New with Java Development Parsing JSON in JAVA Here is my Code.
package com.zenga.control;
import java.io.BufferedReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class Start {
public String readUrl(String urlString) {
String jsonString = null;
try {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(urlString);
client.executeMethod(get);
jsonString = get.getResponseBodyAsString();
}catch(Exception e) {
}
return jsonString;
}
public void getAddAsBeanObject() {
try {
String jsonString = new Start().readUrl("http://myDomain/JsonZ.json");
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Start().getAddAsBeanObject();
}
}
As I successfully Read Value in JSONObject and it also showing all JSON String on console But How can i Get Value For ID and UID and DURATION ?
Here The JSONString the i read in System.out.println(obj);
{
"Demo": {
"CONTENT": [
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
},
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
}
]
}
}
Following code can be used to iterate the JSON objects inside the JSON array 'CONTENT', using .get(java.lang.String) as documented, to pull the value out of the JSONObject.
I have only demonstrated how to get the ID but the same logic applies to the other values.
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT");
java.util.Iterator<?> iterator = content.iterator();
while (iterator.hasNext()) {
JSONObject o = (JSONObject) iterator.next();
System.out.println(o);
System.out.println(o.get("ID"));
// etc...
}
Following is a sample code to reach the array`s inner objects specific to pattern you have provided.
String str = "{"+
"\"Demo\": {"+
"\"CONTENT\": ["+
" {"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" },"+
"{"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" }"+
"]"+
"}"+
"}";
try {
JSONObject jsr = new JSONObject(str); // JSON object with above data
JSONObject demo = jsr.getJSONObject("Demo"); // get Demo which is a JSON object inside jsr.
JSONArray content = demo.getJSONArray("CONTENT");// get CONTENT which is Json array inside Demo
for (int i = 0; i < content.length(); i++) { // iterate over array to get inner JSON objects and extract values inside
JSONObject record = content.getJSONObject(i); // each item of Array is a JSON object
String ID = record.getString("ID");
String UID = record.getString("UID");
String DURATION = record.getString("DURATION");
}
}
catch (JSONException e) {
e.printStackTrace();
}
Note: Above code is specifc to org.Json API. Find appropriate methods in library you are using for Json handling
Use a loop that iterates through the Json Object and access each of the element
for(/**loop until the counter reaches the size of the json object**/) {
//Access each element based on the ID as below.
System.out.println(Demo.CONTENT[CurrentCounter].ID); //here CurrentCounter is index
System.out.println(Demo.CONTENT[CurrentCounter].UID); ..... //read through all ids
}
I guess you could use the 'get' Method on the JSONObject. If you don't know which key to look for, I suggest using a Method that returns all available keys, like the one called 'keys'. With these values, you could then traverse down in you structure. See here:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
I guess GSON will be a big help for you.
See here Parsing json object into a string
There is a samplecode as well
Create a class which have variables you want to read from json string.And Gson will handle the rest.
https://code.google.com/p/google-gson/
Example usage:
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);

Categories