考虑以下是我的数组
[
{"id":10,"name":"name10","valid":true},
{"id":12,"name":"name12","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":9,"name":"name9","valid":true}
]
从中创建了JsonArray
,如下面的代码所示:
//Create a JSON Parser using GSON library
objJsonParser = new JsonParser();
String strArrayText = [{"id":9,"name":"name9","valid":true}, ...]
JsonArray jsonArrayOfJsonObjects = objJsonParser.parse(strArrayText).getAsJsonArray();
现在,我正在尝试根据jsonArrayOfJsonObjects
字段对name
进行排序。
期望的输出:
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
任何人都可以帮助解决这个问题与Java& GSON?
非常感谢您的投入。
答案 0 :(得分:9)
首先,解析JSON的正确方法是创建一个类来封装数据,例如:
public class MyClass {
private Integer id;
private String name;
private Boolean valid;
//getters & setters
}
然后:
Type listType = new TypeToken<List<MyClass>>() {}.getType();
List<MyClass> myList = new Gson().fromJson(strArrayText, listType);
现在您有一个List
,并且您希望按属性id
的值对其进行排序,因此您可以按照here的说明使用Collections
:
public class MyComparator implements Comparator<MyClass> {
@Override
public int compare(MyClass o1, MyClass o2) {
return o1.getId().compareTo(o2.getId());
}
}
最后:
Collections.sort(myList, new MyComparator());
答案 1 :(得分:0)
你可以使用Gson库https://sites.google.com/site/gson/gson-user-guide 获取Array(该类应该实现可比较)并使用arrays.sort();
进行排序由于
答案 2 :(得分:0)
尝试使用此库方法作为创建类的简单 JSON级替代:
/**
* Sort JSON-array by a given key name (numbers or text expected).
*
* @param jsonArray JSON-array to sort.
* @param keyNameToSort Key name to sort by. Expected are integer type
* (sorted ascending) or string type (sorted
* alphabetically).
*/
public static JsonArray
sortJsonArrayByKey(
JsonArray jsonArray,
String keyNameToSort) {
JsonArray sortedJsonArray = new JsonArray();
JsonObject jsonObject = null;
int jsonElementIndex;
TreeMap<Integer, JsonObject> integerSortedObjects = new TreeMap<>();
TreeMap<String, JsonObject> stringSortedObjects = new TreeMap<>();
for (
jsonElementIndex = 0;
jsonElementIndex < jsonArray.size();
jsonElementIndex++) {
try {
// A JSON-Object from JSON-array:
jsonObject =
jsonArray
.get(
jsonElementIndex)
.getAsJsonObject();
} catch (Exception notAnObject) {
}
for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
// Look for the given key in the JSON-object:
if (
entry.getKey()
.equals(keyNameToSort)) {
try {
// If key is of integer type:
integerSortedObjects.put(
entry
.getValue()
.getAsInt(),
jsonObject);
} catch (Exception notAnInt) {
try {
// If key is of string type:
stringSortedObjects.put(
entry
.getValue()
.getAsString(),
jsonObject);
} catch (Exception neitherIntNorString) {
}
}
}
}
}
// Add sorted by number values first:
for (Integer key : integerSortedObjects.keySet()) {
sortedJsonArray.add(
integerSortedObjects.get(
key));
}
// Add sorted by string values second:
for (String key : stringSortedObjects.keySet()) {
sortedJsonArray.add(
stringSortedObjects.get(
key));
}
return sortedJsonArray;
}