Print JSON with ordered properties - java

I have JSON with objects in specific order:
{
"Aaa": {
"Langs": {
"Val": [
"Test"
],
"Pro": [
"Test2"
]
}
},
"Bbb": {
"Langs": {
"Val": [
"Test"
],
"Pro": [
"Test2"
]
}
},
"Ddd": {
"Langs": {
"Val": [
"Test"
],
"Pro": [
]
}
},
}
And I would like to add new object Ccc between Bbb and Ddd. I tried to configure object mapper like this:
ObjectMapper mapper = new ObjectMapper()
.enable(SerializationFeature.INDENT_OUTPUT)
.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
and then print with this code, but Ccc ends at the end of file.
DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
//Write whole JSON in FILE
String finalJson = mapper.writer(prettyPrinter).writeValueAsString(rootFlores);
finalJson = finalJson.replaceAll("\\[ ]", "[" + System.lineSeparator() + " ]");
finalJson = finalJson.replaceAll("/", "\\\\/");
Files.write(Paths.get("DictionaryFlores_new.json"), Collections.singleton(finalJson));
Is here a way how to print JSON ordered?

Jackson deserialization/serialization does not sort properties
According to this answer, the Jackson SORT_PROPERTIES_ALPHABETICALLY only applies to POJO properties, not Maps. In JSON there is no difference between a Map and an Object, so you need to set the order in the Map first by using a LinkedHashMap or TreeMap

By definition, the keys of an object are unordered. I guess some libraries could offer an option to control the order of the keys when stringifying, but I wouldn't count on it.
When you need a certain order in json, you need to use an array. Of course, then you'd have to move the keys to a property in the child objects, and then the resulting array could only be indexed by number (not by the key). So then you might have to do additional processing to covert the data structure in the JSON to the data structure you really want to process.

Since you seems ready to use regex to update a JSON, I would suggest a "safer" approach. Don't try to create a pattern that would unsure that you don't update a value somewhere.
Iterate you values, on object at the time. Stringify the object and append the String yourself. That way, you are in charge of the object order. Example :
StringBuilder sb = new StringBuilder("{");
List<JsonPOJO> list = new ArrayList<>();
//populate the list
for(JsonPOJO pojo : list){
sb.append(pojo.stringify()).append(",");
}
sb.setLength(sb.length() - 1); //remove the last commma
sb.append("}");
Here, you are only managing the comma between each JSON object, not create the "complex" part about the JSON. And you are in full control of the order of the value in the String representation, it will only depend on the way you populate the List.
Note: sorry for the "draft" code, I don't really have access to my system here so just write this snippet to give you a basic idea on how to "manage" a JSON without having to recreating an API completely.
Note2: I would note suggest this unless this looks really necessary. As you mention in a comment, you are have only the problem with one key where you already have a JSON with 80000 keys, so I guess this is a "bad luck" scenario asking for last resort solution ;)

Related

Read the outer-most JSON object but not the inner ones using Jackson?

This is similar to this question but it's a little different.
Let's say I have a json document defined like this:
[
{ "type" : "Type1",
"key1" : "value1" },
{ "type" : "Type2",
"key2" : "value2" }
]
I want to read this json document into a list of strings (List<String>). I only want to read the outer-most list into the Java List, the json objects inside the list should be left as-is inside the list. The result should be equivalent to this (I ignore newlines etc):
var myList = List.of("{\"type\": \"Type1\", \"key1\": \"value1\"}, {\"type\": \"Type2\", \"key2\": \"value2\"}")
Note that I don't want to create any DTO to hold some intermediate representation. I just want everything below the "list" to be represented "as-is".
How can I achieve this?
I'm using Jackson 2.12.1.
If you don't want to hold intermediate representation in a DTO, then one way in which the required deserialization can be achieved is:
// Create a ObjectMapper (of type com.fasterxml.jackson.databind.ObjectMapper)
ObjectMapper mapper = new ObjectMapper();
// Read the json string into a List. This will be deserialized as a collection of LinkedhashMap
List<LinkedHashMap> list = mapper.readValue(getInputString(), List.class);
//Iterate over the deserialized collection and create a JSONObject from every LinkedHashMap
List<String> result = list.stream()
.map(map -> new JSONObject(map).toString())
.collect(Collectors.toList());
This will produce:
[{"key1":"value1","type":"Type1"}, {"key2":"value2","type":"Type2"}]
Downside of this approach is, it takes a hit on performance.

I have to parse JSON response, I have to fetch a child node which is under leet speak (random string which contains symbols, chars, numbers)

I have to parse the JSON response, which has a leet speak, the node which I want to extract is the child of leet speak. am not able to extract the required child form the response.
Ex: following is the JSON structure. from which I want to extract name
"debug": {
"|\"|2()|\\|+3/\\/|)": {
"child1": [],
"child2": {
"Name": "abcd",
"Id": "123"
},
"child3": {
"location": "Delhi"
}
}
}
JSON document is equivalent of the Map, and your leet speak string is a key. That is very bad idea as keys should be easily identifiable. So I would suggest to re-think the structure. May be introduce another level where your leet speak string would be contained as a child under some easily identifiable key. But if you can not do that, you can convert your JSON into Map and then extract ALL keys and then traverse through them and find the one that you need and then get your content by that key
You can create pojo and get that node value
Gson g = new Gson();
Pojo1 p1=g.fromJson(jo.toString(), Pojo1.class);
System.out.println(p1.getDebug().get23().getChild2().getName());

Using GSON to parse Json into a JAVA Object where the Json Elements may vary

I am trying to parse a JSON .txt file into a JAVA object using GSON. The JSON file has the following structure:
{
"event0" : {
"a" : "abc",
"b" : "def"
},
"event1" : {
"a" : "ghi",
"b" : "jkl",
"c" : "mno"
}
}
I have read the text file into a String called dataStr. I want to use the fromJson method to capture the events into the following JAVA class:
public class Event {
private String a;
private String b;
private String c;
public Event() {}
}
The problem is that the JSON might have one extra field "c" in some of the elements. I want to parse all the events into Event class objects, and for the cases where there is no "c" field, I want to make it null or zero in my object. It is not known beforehand which of the elements will have the "c" field.
Specifically, I was not able to figure out how to handle one extra field in some of the JSON elements. I want to do something along the lines of:
Gson gson = new Gson();
ArrayList<Event> events = gson.fromJson(dataStr, Event.class);
But I am stuck with first, how to iterate over the events in the Json file, and secondly, how to handle some occasional missing fields into the same Event object. I would really appreciate a kick in the right direction. Thank you all.
I am fairly new to JSON parsing, and might have missed something in the following answers:
Using Gson to convert Json into Java Object
Mapping JSON into POJO using Gson
Using gson to parse json to java object
Parse JSON into a java object
How to parse a json file into a java POJO class using GSON
I'm not sure if I understood your question right. As per my understanding, you are trying to convert a json object with an extra field which is not available in the java class. Frankly, I don't understand why you want that or if it's possible to start with. You can have a workaround by converting the json to Map.
Map map = gson.fromJson(jsonString, Map.class);
Gson automatically do that for you.
So, if you have a class "Alpha" with 3 fields ("a", "b" and "c") and you try to work on a json object that has 2 fields with names that match with Alpha's "a" and "b", Gson will fill "a" and "b" with json file's value and "c" will automatically set as null.
So, in your case, if you write this:
ArrayList<Event> events = gson.fromJson(dataStr, Event.class);
And in your json there are events with only 2 fields (that match with any Event's class fields) and events with all fields set, you will get a list of Events with no errors. Maybe you'll get some fields null, but the code will work.
I hope to be helpful! Ask for further informations, if you want to!
EDIT
Note that your json file has not to be .txt but .json instead!
First I believe your JSON should look like this:
{
"events": [
{
"name": "event0",
"a": "abc",
"b": "def"
},
{
"name": "event1",
"a": "abc",
"b": "def",
"c": "mno"
}
]
}
This will need two classes for your model:
public List<Event> events = null;
public class Event {
public String name;
public String a;
public String b;
public String c;
}
And then then with GSON
Events events = gson.fromJson(jsonData, Events.class);
Also I recommend to always use an online validator for JSON so you are sure your JSON structure is correct before coding against it.
https://jsonlint.com/
Or for formate the JSON:
http://jsonprettyprint.com/
Also this website can create the Java classes for you from either a JSON Schema or by using an example file.
http://www.jsonschema2pojo.org/
Try the below code snippet:
Gson gson = new Gson();
ArrayList<Event> events = gson.fromJson(dataStr, new TypeToken<ArrayList<Event>>(){}.getType());
In the source code of Gson has a very clear explain

JSON construction

I am new to JSON and getting confused everytime I create a new one.
I am trying to create a JSON array like this :
{
"id":"2003",
"HouseMD" :
{
"Doctor_1": "Thirteen",
"Doctor_2" : "Chase"
"Doctor_n" : "Someone"
}
}
Basically I am trying to add info dynamically from Doctor_1 to Doctor_n" in a for loop. and if I use a JSON Object I am only getting the last value when I finally print it.
How do I get something that I want?
Any help appreciated.
Thanks.
JSON arrays look like this:
{ "id":"2003", "HouseMD" : [{ "Doctor_1": "Thirteen"}, {"Doctor_2" : "Chase"}, {"Doctor_n" : "Someone" }]}
Notice the square bracket that surrounds each JSON object in the array.
Here is the link to the JSON website, which can offer more info:
JSON
Note that in order for the code below to work, you will also need the JSON library, which you can easily download from here Download Java JSON Library
I don't know the approach you are using, but based on the format you want, I would do something like this:
JSONObject data = new JSONObject();
data.put("id", "2003");
JSONObject doctors = new JSONObject();
//here I suppose you have all doctors in a list named doctorList
//and also suppose that you get the name of a doctor by the getName() method
for (int i = 0; i < doctorList.size(); ++i)
{
doctors.put("Doctor_" + (i+1), doctorList.get(i).getName();
}
data.put("HouseMD", doctors);
//then you could write to a file, or on screen just for test
System.out.println(data.toString());
However, I feel you need to become more comfortable with JSON, so try starting here.

Parsing JSON String

I have this JSON file that is read and stored in a String called jsonString and it looks like this:
{
"position":1,
"team_id":10260,
"home":
{
"played":18,
},
},
{
"position":2,
"team_id":8456,
"home":
{
"played":12,
},
},
Code for parsing:
JSONObject obj = new JSONObject(jsonString);
Iterator it = obj.keys();
while(it.hasNext()){
String s = it.next().toString();
System.out.print(s + " " + obj.getString(s) + " ");
}
Output is: position 1 home {"played":18} team_id 10260
So it doesn't read the rest of the file. Can you tell me what is the problem? And also, why home {"played":18} is printed before team_id 10260?
If you look at the way your brackets are organized, you can see that your String actually contains several JSON objects, and the construction stops after the first complete one.
As for your second question, Iterators seldom have a guaranteed order, so you can't make any assumptions about which order the elements will be returned in.
The order will be dependent on the type of Map that JSONObject uses; could be indeterminate, or could be by the key's codepoint, or could be in order read, depending on, e.g. HashMap, TreeMap or LinkedHashMap.
Other than that, there are two objects serialized and JSONObject has apparently just stopped after the first one. You may need to wrap the entire input in a set of { }.

Categories