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");
}
Related
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 2 years ago.
Any idea how I can parse a Json like this into a java entity?
{
"-MR0myiEK5jDOdthWeMT": {
"birthday": "Date5",
"name": "Check 1"
},
"-MR0n-86JCqxuO7C2HfZ": {
"birthday": "Date3",
"name": "Check 2"
},
"-MR0n0VCXBw-32tfq738": {
"birthday": "Date1",
"name": "Check 4"
}
}
I am using spring and wanted to parse it into a java class like this:
class Person{
String name;
String birthday;
}
The org.json library is easy to use.
Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation
[ … ] represents an array, so library will parse it to JSONArray
{ … } represents an object, so library will parse it to JSONObject
Example code below:
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("birthday");
......
}
I would use the
jackson
library that is already included in the spring boot dependencies.
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());
}
}
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));
}
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I have a JSON string and I need to extract a string from it using Java (android)
The JSON string look like that :
{
"Header": {
"context": {
"change": {
"token": 3191
},
"_jsns": "urn:zimbra"
}
},
"Body": {
"AuthResponse": {
"authToken": [
{
"_content": "token"
}
],
"lifetime": 43199998,
"_jsns": "urn:zimbraAdmin"
}
},
"_jsns": "urn:zimbraSoap"
}
I want to get the value of _content, which is "token" is this case.
What i tried:
NB: result contains the json string
//result contains the json string
JSONObject jObject = new JSONObject(result);
String aJsonString = jObject.getString("Body");
JSONObject jResult = new JSONObject(aJsonString);
String aaa = jResult.getString("authToken");
At this point I get the following error :
W/System.err: org.json.JSONException: No value for authToken
Any help will be appreciated
EDIT : Java code updated
You need to traverse the JSON tree step by step
JSONObject jObject = new JSONObject(result);
JSONObject jBody = jObject.getJSONObject("Body");
JSONObject jAuthResponse = jBody.getJSONObject("AuthResponse");
JSONArray jauthToken = jAuthResponse.getJSONArray("authToken");
JSONObject jFirst = jauthToken.getJSONObject(0);
String aJsonString = jObject.getString("_content");
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);