How to output JSON string in formatted form? [duplicate] - java

This question already has answers here:
Pretty-Print JSON in Java
(20 answers)
Closed 5 years ago.
For example, I want to print it as below, instead of one single line. This is a JSON string. By default, myJsonObject.toString() is a one-line String. Is there some method from org.json.JSONObject that can directly output this formatted form?
{
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}

There are different ways to print pretty json string.
GSON offers a method setPrettyPrinting(),
For instance,
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonElement = new JsonParser().parse(jsonString);
System.out.println(gson.toJson(jsonElement));

To indent any old JSON, just bind it as Object, like:
ObjectMapper mapper = new ObjectMapper();
Object json = mapper.readValue(myJsonObject, Object.class);
and then write it out with indentation:
String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

Related

Parsing JSON to Java Entity [duplicate]

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.

is there an json simple function to get all the keys from a jsonobject?

I'm trying for the first time to use the jsonsimple library on java.
So i formatted a json object using a String.
the Object is the following
{
"mario":{
"city": "rome",
"birth": 1980,
"haircolor": "blonde"
},
"Lucas": {
"city": "milan",
"birth": 1985,
"haircolor": "brown"
}
}
From these object i need to get the names in a String format.
Thanks everyone for any kinda of help.
JsonObject implements java.util.Map, so you can simply call the keySet-Method on your JsonObject.
Example:
JsonObject myJsonObject = ...;
Set<String> allNamesInThisObject = myJsonObject.keySet();

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));
}

Is there any tool to generate a String from a JSON?

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()

Categories