How to Sort Json Object in Java

How to sort JSON object in java?

Parse these JSON to Collection of Objects and use comparator to sort it using your preferred field.

  • Use GSON to parse it to collection of objects

Example:

import com.google.gson.Gson;

class Person {
private int age;
private String name;
}

String json = "{'age':22,'name':'Jigar'}";
Gson gson = new Gson();
TestJsonFromObject obj = gson.fromJson(json, Person.class);

If you want to create JSON from Object.

Person p = new Person();
p.setName("Jigar");
p.setAge(22);
String jsonStr = new com.google.gson.Gson().toJson(obj);

JAVA Sort JSONObject (String,Int) in descending order

Here is the solution of your problem. I hope this will help.

import org.json.JSONException;

import org.json.JSONObject;

import java.util.*;

public class sample {
private static class MyModel {
String key;
int value;

MyModel(String key, int value) {
this.key = key;
this.value = value;
}
}

public static void main(String[] args) {
List<MyModel> list = new ArrayList<>();

try {
//here is you json object
JSONObject obj = new JSONObject();
obj.put("name1", 29);
obj.put("name2", 26);
obj.put("name3", 29);
obj.put("name4", 27);

//parsing your json
Iterator<?> keys = obj.keys();
MyModel objnew;
while (keys.hasNext()) {
String key = (String) keys.next();
objnew = new MyModel(key, obj.optInt(key));
list.add(objnew);
}

//sorting the values
Collections.sort(list, new Comparator<MyModel>() {
@Override
public int compare(MyModel o1, MyModel o2) {
return Integer.compare(o2.value, o1.value);
}
});
//print out put
for (MyModel m : list) {
System.out.println(m.key + " : " + m.value);
}

} catch (JSONException e) {
e.printStackTrace();
}
}

}

Sort JSON objects by key in Java

There are not many ways to to what you want to achieve. Refelection API is there but it comes with many drawbacks and not very reliable and straightforward. However, the most reliable and easy way is to use instanceof operator.

With this method you have full control over every conversion and comparison, also you can compare custom classes with compareTo() method implemented. Unless you have too many possibilities to cover, this maybe the best approach.

I assume that you know that JSONObject.get() method converts object into Object types so add conditions like

Object obj1 = a.get(KEY_NAME);
Object obj2 = b.get(KEY_NAME);

if(obj1 instanceof Integer && obj2 instanceof Integer){
return ((Integer) obj1).compareTo(((Integer) obj2));
} else if(obj1 instanceof Double && obj2 instanceof Double){
return ((Double) obj1).compareTo(((Double) obj2));
} else if(obj1 instanceof Double || obj2 instanceof Double){
Double v1 = ((Number) obj1).doubleValue();
Double v2 = ((Number) obj2).doubleValue();
return v1.compareTo(v2);
}

As Number class is super class of Integer, Float and Double, so you
can convert it from there.

It may induce lot of code but will add reliability but no surprises when unexpexcted JSON is encountered. Also additional conditions would be able handle to handle mismatching data types and and could also detect error in JSON object.

Sort Json based on multiple values

You should essentially have a comparator method like this, in your POJO object.

public int compareTo(Object obj) {
if(obj == null)
return 1;
else if (obj instanceof Person)
{
Person p2 = (Person) obj;
if(this.gender.compareTo(p2.gender) < 0)
return 1;
else if(this.gender.compareTo(p2.gender) == 0)
return this.age.compareTo(p2.age);
else
return -1;
}
else return 1;

}

It will sort first on the basis of Gender and then age, this is what I understand from your sample output.

From your JSON object convert to POJO object like this.

List<Person> personList = new ArrayList<>();
Person p =new GSON().fromJson(String , yourPOJO.class); // do this for all inputs
personList.add(p);

then you need to sort using

Collections.sort(personList);

hope this helps!

Good luck!

How to sort json array elements in java

Here is a solution

i need to call readTree, that use JsonNodeFactory

and then convert to string by writeValueAsString

Here a code

public static String writeAsSortedJson(Object object) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setNodeFactory(getArrayNodeKeyValueSortingNodeFactory());

mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

String preparedJson = mapper.writeValueAsString(object);
JsonNode jsonNode = mapper.readTree(preparedJson);

return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
}

@SuppressWarnings("JavaNCSS")
public static JsonNodeFactory getArrayNodeKeyValueSortingNodeFactory() {
return new JsonNodeFactory() {
@Override
public ObjectNode objectNode() {
return new ObjectNode(this, new TreeMap<String, JsonNode>());
}

@SuppressWarnings("JavaNCSS")
@Override
public ArrayNode arrayNode() {
return new ArrayNode(this, new SortedArrayList<JsonNode>(new Comparator<JsonNode>() {
@Override
public int compare(final JsonNode o1, final JsonNode o2) {
return compareRecursively(o1, o2);
}

private int compareRecursively(final JsonNode o1, final JsonNode o2) {
if (o1.isObject() && o2.isObject()) {
return compareObjectNodes(o1, o2);
} else if (o1.isObject()) {
return 1;
} else if (o2.isObject()) {
return -1;
} else if (o1.isArray() && o2.isArray()) {
return compareArrayNodes(o1, o2);
} else if (o1.isArray()) {
return 1;
} else if (o2.isArray()) {
return -1;
}
return o1.asText().compareTo(o2.asText());
}

private int compareArrayNodes(final JsonNode o1, final JsonNode o2) {
List<JsonNode> elements1 = Lists.newArrayList(o1.elements());
List<JsonNode> elements2 = Lists.newArrayList(o2.elements());

for (int i = 0; i < elements1.size() || i < elements2.size(); i++) {
if (i >= elements1.size()) {
return -1;
} else if (i >= elements2.size()) {
return 1;
}

JsonNode jsonNode1 = elements1.get(i);
JsonNode jsonNode2 = elements2.get(i);
int compareRecursively = compareRecursively(jsonNode1, jsonNode2);
if (compareRecursively != 0) {
return compareRecursively;
}
}

return 0;
}

@SuppressWarnings("ReturnCountExtended")
private int compareObjectNodes(JsonNode o1, JsonNode o2) {
List<Map.Entry<String, JsonNode>> elements1 = Lists.newArrayList(o1.fields());
List<Map.Entry<String, JsonNode>> elements2 = Lists.newArrayList(o2.fields());
if (elements1.isEmpty() && elements2.isEmpty()) {
return 0;
} else if (elements1.isEmpty()) {
return -1;
} else if (elements2.isEmpty()) {
return 1;
}

for (int i = 0; i < elements1.size() || i < elements2.size(); i++) {
if (i >= elements1.size()) {
return -1;
} else if (i >= elements2.size()) {
return 1;
}

Map.Entry<String, JsonNode> entry1 = elements1.get(i);
Map.Entry<String, JsonNode> entry2 = elements2.get(i);
int compare = entry1.getKey().compareTo(entry2.getKey());
if (compare == 0) {
int compareRecursively = compareRecursively(entry1.getValue(), entry2.getValue());
if (compareRecursively != 0) {
return compareRecursively;
}
} else {
return compare;
}
}

return 0;
}
}) { });
}
};
}

public static class SortedArrayList<T> implements List<T> {
private final List<T> delegate = new ArrayList<>();
private final Comparator<T> comparator;

public SortedArrayList(Comparator<T> comparator) {
this.comparator = comparator;
}

@Override
public int size() {
return delegate.size();
}

@Override
public boolean isEmpty() {
return delegate.isEmpty();
}

@Override
public boolean contains(final Object o) {
return delegate.contains(o);
}

@NotNull
@Override
public Iterator<T> iterator() {
return delegate.iterator();
}

@NotNull
@Override
public Object[] toArray() {
return delegate.toArray();
}

@NotNull
@Override
public <T1> T1[] toArray(@NotNull final T1[] a) {
return delegate.toArray(a);
}

@Override
public boolean add(final T t) {
boolean add = delegate.add(t);
sort();
return add;
}

@Override
public void add(final int index, final T element) {
delegate.add(index, element);
sort();
}

@Override
public boolean remove(final Object o) {
boolean remove = delegate.remove(o);
sort();
return remove;
}

@Override
public T remove(final int index) {
T remove = delegate.remove(index);
sort();
return remove;
}

@Override
public boolean containsAll(@NotNull final Collection<?> c) {
return delegate.containsAll(c);
}

@Override
public boolean addAll(@NotNull final Collection<? extends T> c) {
boolean addAll = delegate.addAll(c);
sort();
return addAll;
}

@Override
public boolean addAll(int index, @NotNull Collection<? extends T> c) {
boolean addAll = delegate.addAll(index, c);
sort();
return addAll;
}

@Override
public boolean removeAll(@NotNull final Collection<?> c) {
boolean removeAll = delegate.removeAll(c);
sort();
return removeAll;
}

@Override
public boolean retainAll(@NotNull final Collection<?> c) {
boolean retainAll = delegate.retainAll(c);
sort();
return retainAll;
}

@Override
public void clear() {
delegate.clear();
}

@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SortedArrayList<?> that = (SortedArrayList<?>) o;
return Objects.equals(delegate, that.delegate);
}

@Override
public int hashCode() {
return Objects.hash(delegate);
}

@Override
public T get(final int index) {
return delegate.get(index);
}

@Override
public T set(final int index, final T element) {
delegate.set(index, element);
sort();
return element;
}

@Override
public int indexOf(final Object o) {
return delegate.indexOf(o);
}

@Override
public int lastIndexOf(final Object o) {
return delegate.lastIndexOf(o);
}

@NotNull
@Override
public ListIterator<T> listIterator() {
return delegate.listIterator();
}

@NotNull
@Override
public ListIterator<T> listIterator(final int index) {
return delegate.listIterator(index);
}

@NotNull
@Override
public List<T> subList(final int fromIndex, final int toIndex) {
return delegate.subList(fromIndex, toIndex);
}

private void sort() {
delegate.sort(comparator);
}
}

How to sort JSONOBJECT by a string?

here you are sorting the string value but i think overall_league_position value always get in integer so your sorting is not working.

for this sorting you can try below code

Collections.sort(movieList, new Comparator<Movie>() {
@Override
public int compare(Movie lhs, Movie rhs) {
return Integer.parseInt(lhs.getPosition()) - Integer.parseInt((rhs.getPosition()));
}
});


Related Topics



Leave a reply



Submit