在Gson中反序列化有序List

时间:2014-04-02 11:17:08

标签: android json deserialization gson json-deserialization

我在Android中使用Gson库。我以json格式从Web服务中检索一些数据。

所以我得到了以下数据:

Gson gson = new GsonBuilder().create();
ClassA obj = gson.fromJson(returnFromServer.toString(), ClassA.class);

ClassA类是:

public class ClassA{
    private String id;
    private List<ClassB> myList;
}

所以我在obj中有一个自定义对象列表。

问题是:我可以确定列表的顺序与json文件中元素的顺序相同吗?如果没有,Gson中是否有任何机制允许维持json文件的相同顺序?

注意:以前的所有尝试都会产生一个按照json文件的顺序排序的列表。

1 个答案:

答案 0 :(得分:0)

您可以使用LinkedList实现来维护排序顺序,但是我创建了一个简单的程序,即使在ArrayList中也保持顺序。您可以查看以下代码,

我创建了ClassB.java

package com.zack.demo;

public class ClassB {

    private String name;

    private int age;

    private String gender;


    public ClassB(String name, int age, String gender)
    {
        this.name = name;
        this.age = age;
        this.gender = gender;

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

}

ClassA.java

package com.zack.demo;

import java.util.List;

public class ClassA {

    private String id;
    private List<ClassB> myList;

    public ClassA(String id, List<ClassB> myList)
    {
        this.id = id;
        this.myList = myList;
    }

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public List<ClassB> getMyList() {
        return myList;
    }
    public void setMyList(List<ClassB> myList) {
        this.myList = myList;
    }



}

列表订单的示例测试程序

package com.zack.demo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.google.gson.Gson;

public class GsonTest {

    public static void main(String[] args) {

        Gson gson = new Gson();


        ClassB o2 = new ClassB("Test2", 20, "Male");
        ClassB o1 = new ClassB("Test1", 10, "Male");


        List<ClassB> ls = new LinkedList<ClassB>();

        ls.add(o2);
        ls.add(o1);

        ClassA  a1 = new ClassA("T1", ls);

        String result = gson.toJson(a1, a1.getClass());

        System.out.println(result);

        ClassA obj = gson.fromJson(result.toString(), ClassA.class);

        System.out.println(gson.toJson(obj, obj.getClass()));




    }

}

结果

{"id":"T1","myList":[{"name":"Test2","age":20,"gender":"Male"},{"name":"Test1","age":10,"gender":"Male"}]}
{"id":"T1","myList":[{"name":"Test2","age":20,"gender":"Male"},{"name":"Test1","age":10,"gender":"Male"}]}