Home > OS >  How to reposition or reorder the keys in JSON object or hash map in java
How to reposition or reorder the keys in JSON object or hash map in java

Time:12-25

{
data:{},
firstNane:"",
id:"1,
lastName:"",
  children:[
    parent:"1",
    id:"11",
    name:"",
    firstName:"",
    lastName:"",
    chidlren:[..other nested children],
    data:{},
  ],
name:"",
}

Above is my JSON object, I want to reposition the keys into the following format id,name,firstName,lastName,data and children

Could some one let me know how can I do the reposition the keys as mentioned above so my final output would be display as follows ::-

This is the JSON object also let me know how it would be possible for the hash map to order the elements.

{
    id:"1,
    name:"",
    firstNane:"",
    lastName:"",
    data:{},
      children:[
        id:"11",
        name:"",
        firstName:"",
        lastName:"",
        parent:"1",
        data:{},
        chidlren:[..other nested children],
      ],

}

CodePudding user response:

You can order the elements using a LinkedHashMap.

The LinkedHashMap returns the elements in the same way they are added, unlike HashMap.

CodePudding user response:

By JSON definition:

JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

An object is an unordered set of name/value pairs.

Similarly, HashMap is not ordered either: This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Next, the presented JSON is invalid and needs to be updated.

However, certain JSON libraries provide facilities to sort the fields for example, @JsonPropertyOrder annotation in Jackson library.

@JsonInclude(Include.NON_NULL)
@JsonPropertyOrder({ "id", "name", "firstName", "lastName", "parent", "data", "children" })
@Data
public class MyPojo {
    private Integer id;
    private String name;
    private String firstName;
    private String lastName;
    private Map<String, Object> data;
    private List<MyPojo> children;
    private Integer parent;
}

Test:

ObjectMapper mapper = new ObjectMapper();
MyPojo c1 = new MyPojo(11, "", "", "", new HashMap<>(), new ArrayList<>(), 1);
MyPojo mp = new MyPojo(1, "", "", "", new HashMap<>(), Arrays.asList(c1), null);

System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mp));

Output:

{
  "id" : 1,
  "name" : "",
  "firstName" : "",
  "lastName" : "",
  "data" : { },
  "children" : [ {
    "id" : 11,
    "name" : "",
    "firstName" : "",
    "lastName" : "",
    "parent" : 1,
    "data" : { },
    "children" : [ ]
  } ]
}
  • Related