0

I have a String which is in JSON format. I need to sort this JSON string using attributes but am unable to do it. JSON String is created by reading a CSV file. I do not want to read the CSV again and have to implement it using JSON String only. Is there a way to do that? Please let me know.

JSON String format is :

[
  {
    "address": "some address",
    "name": "some name",
    "phone": "some phone",
    "age": "some age",
    "SSN": "some SSN"
  },
  {
    "address": "abc",
    "name": "def",
    "phone": "ghi",
    "age": "jkl",
    "SSN": "mno"
  }
]

Please explain.

1
  • you mean "sort this JSON string using attributes" as e.g. to sort the above entries in alphabetical order by address? Commented Oct 12, 2016 at 7:42

1 Answer 1

1

You can convert the JSONstring into a TreeMap with a Comparator you implement to compare by value, and then convert this TreeMap back to JSON.

See how to create a value Comparator here: http://www.programcreek.com/2013/03/java-sort-map-by-value/

And then use ObjectMapper to convert the JSON into a map the the map back to JSON:

String json = "{\"address\" : \"def\","
    + "\"name\" : \"ghi\","
    + "\"phone\" : \"jkl\","
    + "\"age\" : \"def\","
    + "\"SSN\" : \"abc\"}";

Map<String, String> jsonMap = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
jsonMap = (mapper.readValue(json, Map.class));
Comparator<String> comparator = new ValueComparator(jsonMap);
Map<String, String> treeMap = new TreeMap<String, String>(comparator); 
treeMap.putAll(jsonMap);
String sortedJson = mapper.writeValueAsString(treeMap);

System.out.println(sortedJson);

Result: {"SSN":"abc","address":"def","name":"ghi","phone":"jkl"}

Comparator:

public class ValueComparator implements Comparator<String> {

   Map<String, String> map = new HashMap<String, String>();

   public ValueComparator(Map<String, String> map){
     this.map = map;
   }

   @Override
   public int compare(String s1, String s2) {
     return map.get(s1).compareTo(map.get(s2));
   }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.