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.
Related
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:
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");
}
My doubt is if there is any tool on-line or not to generate a string from a JSON. For example, I have this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
If I want to declare a String in my code with this values, so I have to write many quotation marks to have my JSON in a String acceptable format.
So I want to know if thre is some tool to generate this String?
Some good choices are:
Jackson
Gson
They have built in methods to do just whatever you need to do in an efficient way...
I can't quite tell what you want from your original question, but I assume you are trying to output a Java String that contains some JSON that you have generated.
You should use JSONObject and JSONArray to accomplish this.
To create this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
You should use this code:
JSONObject a = new JSONObject();
a.put("number", 20);
a.put("name", "androider");
JSONObject b = new JSONObject();
b.put("id", 3432);
b.put("name", "other_name");
JSONArray array = new JSONArray();
array.put(a);
array.put(b);
JSONObject root = new JSONObject();
root.put("my_json", array);
// convert the root object to a string with 4 spaces of indentation
String json = root.toString(4);
As told by Angel, Jackson and Gson are two cool libs.
Gson is very easy to use while Jackson has better performance.
Try here, Go through the answers mentioned below
How to convert String to JSONObject in Java
in short,
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
Here put your own string.
Edit:
Try here,
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
Create a Json object,
JSONObject jsonobj = new JSONObject();
Put your data using...
josnobj.put()