如何根据密钥对GSON数组进行排序

如何根据密钥对GSON数组进行排序

本文介绍了如何根据密钥对GSON数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下是我的Array

  [
{id:10,name: name10,valid:true},
{id:12,name:name12,valid:false},
{id:11, :name11,valid:false},
{id:9,name:name9,valid:true}
]

创建一个 JsonArray ,如下代码所示:

  //使用GSON库创建一个JSON解析器
objJsonParser = new JsonParser();
String strArrayText = [{id:9,name:name9,valid:true},...]
JsonArray jsonArrayOfJsonObjects = objJsonParser.parse(strArrayText).getAsJsonArray );

现在,我正在尝试对 jsonArrayOfJsonObjects 基于名称字段。



所需输出:

  [
{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?


你的输入值得我们极大的赞赏。

首先,解析正确的方法你的JSON是创建一个类来封装你的数据,比如:

  public class MyClass {
private Integer id ;
私人字符串名称;
私有布尔有效;
// getters& setters
}

然后:

 输入listType = new TypeToken< List< MyClass>>(){} .getType(); 
列表< MyClass> myList = new Gson()。fromJson(strArrayText,listType);






现在你有一个 List ,你想按属性 id 的值排序,所以你可以使用 Collections 如所示:

  public class MyComparator实现比较器< MyClass> {
@Override
public int compare(MyClass o1,MyClass o2){
return o1.getId()。compareTo(o2.getId());


$ / code $ / pre
$ b $ p

最后:

  Collections.sort(myList,new MyComparator()); 


Consider the following is my Array

[
  {"id":10,"name":"name10","valid":true},
  {"id":12,"name":"name12","valid":false},
  {"id":11,"name":"name11","valid":false},
  {"id":9,"name":"name9","valid":true}
]

Created a JsonArray out of it, like following code does:

//Create a JSON Parser using GSON library
objJsonParser = new JsonParser();
String strArrayText = [{"id":9,"name":"name9","valid":true}, ...]
JsonArray jsonArrayOfJsonObjects = objJsonParser.parse(strArrayText).getAsJsonArray();

Now, I am trying to sort jsonArrayOfJsonObjects based on name field.

Desired Output:

[
  {"id":9,"name":"name9","valid":true},
  {"id":10,"name":"name10","valid":false},
  {"id":11,"name":"name11","valid":false},
  {"id":12,"name":"name12","valid":true}
]

Could anyone help to sort this out with best apporach with respect to Java & Gson?
Your inputs are greatly appreciated.

解决方案

First of all, the proper way to parse your JSON is to create a class to encapsulate your data, such as:

public class MyClass {
    private Integer id;
    private String name;
    private Boolean valid;
    //getters & setters
}

And then:

Type listType = new TypeToken<List<MyClass>>() {}.getType();
List<MyClass> myList = new Gson().fromJson(strArrayText, listType);


Now you have a List and you want to sort it by the value of the attribute id, so you can use Collections as explained here:

public class MyComparator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass o1, MyClass o2) {
        return o1.getId().compareTo(o2.getId());
    }
}

And finally:

Collections.sort(myList, new MyComparator());

这篇关于如何根据密钥对GSON数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:46