且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在java中对JSON对象进行排序?

更新时间:2023-12-04 18:20:23

将这些JSON解析为对象集合并使用比较器使用首选字段对其进行排序。

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

示例:

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);  

如果你想从Object创建JSON。

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);