If you don't want to create POJOs for your data model, you can use javax.json.json-api library to work directly with JSON.
See my maven file (after the code example) for the list of dependencies I added to my project.
package so;
import java.io.StringReader;
import java.io.StringWriter;
import javax.json.*;
public class SortExample {
public JsonObject sortProductsByPrice(JsonObject order) {
JsonArray products = order.getJsonArray("products");
JsonArray details = order.getJsonArray("details");
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
products.stream().sorted((product1, product2) -> {
JsonNumber cost1 = product1.asJsonObject().getJsonNumber("cost");
JsonNumber cost2 = product2.asJsonObject().getJsonNumber("cost");
return Double.compare(cost1.doubleValue(), cost2.doubleValue());
}).forEach((value) -> arrayBuilder.add(value));
JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
objectBuilder.add("products", arrayBuilder.build());
objectBuilder.add("details", details);
return objectBuilder.build();
}
public static void main(String[] args) {
String orderString =
"{\"products\": [ {\"Name\": \"Marble\",\"cost\": 47.49 }, { \"Name\": \"Mixer\", \"cost\": 59.99 }, { \"Name\": \"Soap\", \"cost\": 3.99 } ], \"details\" : [ { \"area\" : 1090.098 } ] }";
JsonObject order = Json.createReader(new StringReader(orderString)).readObject();
JsonObject sortedOrder = new SortExample().sortProductsByPrice(order);
StringWriter writer = new StringWriter();
Json.createWriter(writer).writeObject(sortedOrder);
System.out.println(writer.toString());
}
}
Prints:
{"products":[{"Name":"Soap","cost":3.99},{"Name":"Marble","cost":47.49},{"Name":"Mixer","cost":59.99}],"details":[{"area":1090.098}]}
The main method in my example just constructs the payload from your example. The work is done in sortProductsByPrice.
It just leaves the products in their JsonValue representation and uses the streaming API to sort them and then place them back into a new JsonArray and finally builds up a new JsonObject with original details and sorted products.
I'm not familiar with javax.json and couldn't find a pretty print option. Perhaps a better library is available. But this gives you the gist of what you want to do.
Dependencies:
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.4</version>
</dependency>