How to fluently parse and traverse JSON objects in Java [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I currently use json-simple library in Java to work with JSON objects. Most of the time I get JSON string from some external web service and need to parse and traverse it. Even for some not too complex JSON objects that might be pretty long typing exercise.
Let's assume I got following string as responseString:
{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
],
"title": "some company",
"headcount": 3
}
To get last name of 3d employee I'll have to:
JSONObject responseJson = (JSONObject) JSONValue.parse(responseString);
JSONArray employees = (JSONArray) responseJson.get("employees");
JSONObject firstEmployee = (JSONObject) employees.get(0);
String lastName = (String) firstEmployee.get("lastName");
Something like that at least. Not too long in this case, but might get complicated.
Is there any way for me (maybe switching to some other Java library?) to get more streamlined fluent approach working?
String lastName = JSONValue.parse(responseString).get("employees").get(0).get("lastName")
I can't think of any auto-casting approach here, so will appreciate any ideas.

Try Groovy JsonSlurper
println new JsonSlurper().parseText(json).employees[0].lastName
Output:
Doe
But best solution is JsonPath - with typing
String name = JsonPath.parse(json).read("$.employees[0].lastName", String.class);
System.out.println(name);

Related

Parsing JSON response using Java [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 3 years ago.
How to parse this json response using Java
{
"Name": {
"name_description": "NIL",
"date": "NIL"
},
"Age": {},
"City": {},
"SOAP": [
["content", "subtopic", "topic", "code"],
["I advised her to call 911, which he did.", "history of present illness", "subjective", "{}"]
]
}
You'd have to use an external library like json-simple
Read more about it here
Use a library called org.json, it is honestly the best java json library.
for example:
import org.json.JSONObject;
private static void createJSON(boolean prettyPrint) {
JSONObject tomJsonObj = new JSONObject();
tomJsonObj.put("name", "Tom");
tomJsonObj.put("birthday", "1940-02-10");
tomJsonObj.put("age", 76);
tomJsonObj.put("married", false);
// Cannot set null directly
tomJsonObj.put("car", JSONObject.NULL);
tomJsonObj.put("favorite_foods", new String[] { "cookie", "fish", "chips" });
// {"id": 100001, "nationality", "American"}
JSONObject passportJsonObj = new JSONObject();
passportJsonObj.put("id", 100001);
passportJsonObj.put("nationality", "American");
// Value of a key is a JSONObject
tomJsonObj.put("passport", passportJsonObj);
if (prettyPrint) {
// With four indent spaces
System.out.println(tomJsonObj.toString(4));
} else {
System.out.println(tomJsonObj.toString());
}
}

How do I extract the specific date out in Java? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I am currently using bufferreader to read an API documentation. Below is part of the output:
"number": 88,
"results": [
{
"time": "2013-04-15T18:05:02",
"name": "..."
},
{
"time": "2013-05-01T18:05:00",
"name": "..."
},
...
]
If I want to extract only "2013-04-15T18:05:02", which is the date. How can I do that?
You can use minimal json.
The following snippet extracts the dates and id's of all items:
JsonObject object = Json.parse(output).asObject();
JsonArray results = object.get("results").asArray();
for (JsonValue item : results) {
String date = item.asObject().getString("date", "");
String id = item.asObject().getString("id", "");
...
}
The format of your string seems to be JSON. You can use Jackson API to parse the JSON string into an array. If you don't want to use Jackson or other JSON API, you can still do it using some of the java.util.String class methods. Checkout the following sample:
List<String> dates = new ArrayList<String>();
String results = jsonString.substring(jsonString.indexOf("results"));
while((int index = results.indexOf("\\"date\\"")) != -1) {
String date = results.substring(results.indexOf(':', index), results.indexOf(',', index)).replaceAll(" ", "").replaceAll("\\"", "");
dates.add(date);
results = results.substring(results.indexOf(',', index));
}

json array to individual strings

Assignment: I am using json-simple. How can I convert this json data into individual java strings?
(Please forgive me if you think that this is a low-level question - I am new to JSON, so I don't know much about that - I've searched a lot, but I couldn't find any answers)
I can get the data if there is only one object ... like this ...
{
"name": "Abhi",
"age": "21"
}
But, I can't get the data if it is in the array
[{
"name": "Abhi",
"age": "21"
}, {
"name": "shek",
"age": "7"
}]
my program logic for json object
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("A:/c/dataFile.json"));
JSONObject jObj = (JSONObject) obj;
String gName = (String) jObj.get("name");
String gAge = (String) jObj.get("age");
System.out.println(gName);
System.out.println(gAge);
Can anyone show me how to get the data? maybe a code snippet?
Thanks in advance for your answer!
Because in your second case you are getting JSONArray
you may need to check the instance of obj as
if (jObj instanceof JSONObject)
else if (jObj instanceof JSONArray)

Parsing JSON in Java when two fields are the same? [duplicate]

This question already has answers here:
Parsing JSON Array within JSON Object
(5 answers)
Closed 6 years ago.
Apologies, I have tried multiple things here and seem to run into some issues. This should be simple.
JSON file :
{
"content": [
{
"media_type": "text/html",
"text": "<p>Hello world</p>"
},
{
"media_type": "text/plain",
"text": "Hello world"
}
],
"id": "123",
"title": "no-title"
}
I have a JSONObject created from this string.
I have tried -
String txtFromJSON = json.getJSONObject("content").getJSONObject("text").toString();
String txtFromJSON = json.getString("content.text");
String txtFromJSON = json.getString("content");
All of these fail.
The output I would like is simply the
<p>Hello world<p>
from the first text field.
Is there any simple way for me to get this data stored in a variable?
Thanks.
try this:
final JSONObject obj = new JSONObject(youJsonString);
final JSONObject content = obj.getJSONArray("content");
final int n = content.length();
if(n ==1 ){
String txtFromJSON = json.getString("text");
}

Converting a specific JSON to java object format? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 9 years ago.
Iam new to java script and JSON, please help me in solving my problem. Below is the structure of my JSON in JavaScript
{
"name": "sample",
"def": [
{
"setId": 1,
"setDef": [
{
"name": "ABC",
"type": "STRING"
},
{
"name": "XYZ",
"type": "STRING"
}
]
},
{
"setId": 2,
"setDef": [
{
"name": "abc",
"type": "STRING"
},
{
"name": "xyz",
"type": "STRING"
}
]
}
]
}
in the backend, what should be the synatx of java method to receive this data
public void getJsonData(****){
}
How to parse this JSON data in java and what should be the syntax of method parameter ?
update 1: Edited the json format to make it valid
First create a class that will map your json object and give a name something like "DataObject". Then use the gson library and do the following:
String s = "";
DataObject obj = gson.fromJson(s, DataObject.class);
Your JSON is invalid, but assuming you fix that then you are looking for a library in Java which will serialize an annotated Java class to JSON, or deserialize JSON data to an annotated Java class.
There is a whole list of suitable libraries here:
http://json.org/java/

Categories