简体   繁体   English

GSON:使用java.util.TreeSet序列化对象

[英]GSON: Serialize object with java.util.TreeSet

How can I serialize a TreeSet properly? 如何正确序列化TreeSet? In order to give you an idea of what's not working I've set up this little demo project. 为了让您了解什么不起作用,我已经设置了这个小小的演示项目。 The main goal is to print a JSON string of my QData object. 主要目标是打印我的QData对象的JSON字符串。

App.java App.java

package de.company.gsonserializer;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

public class App 
{
    public static void main( String[] args )
    {
        QData qdata = new QData();

        ArrayList<LData> arrayList = new ArrayList<LData>(1);

        LData l = new LData();
        Map<String, String> unsortedBuabList = new HashMap<String, String>();
        for (int i = 0; i < 5; i++) {
            unsortedBuabList.put("Key-" + i, "Value" + i);
        }
        SortedSet<Map.Entry<String, String>> sortedBuabList = new TreeSet<Map.Entry<String, String>>(
                new Comparator<Map.Entry<String, String>>() {
                    public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
                        return e1.getValue().compareTo(e2.getValue());
                    }
                });
        sortedBuabList.addAll(unsortedBuabList.entrySet());
        l.setBuabList(sortedBuabList);

        arrayList.add(l);
        qdata.setLocations(arrayList);

        System.out.println( qdata.toString() );
    }
}

QData.java QData.java

package de.it2media.gsonserializer;

import java.util.ArrayList;

import com.google.gson.Gson;

public class QData {

    private ArrayList<LData> locations = new ArrayList<LData>(0);

    public ArrayList<LData> getLocations() {
        return locations;
    }

    public void setLocations(ArrayList<LData> locations) {
        this.locations = locations;
    }

    @Override
    public String toString(){
        Gson gson = new Gson();
        String thisObj = gson.toJson(this);
        return thisObj;     
    }

}

LData.java LData.java

package de.it2media.gsonserializer;

import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Map.Entry;

public class LData {

    private SortedSet<Entry<String, String>> buabList = new TreeSet<Map.Entry<String, String>>();

    public SortedSet<Entry<String, String>> getBuabList() {
        return buabList;
    }

    public void setBuabList(SortedSet<Entry<String, String>> buabList) {
        this.buabList = buabList;
    }

}

The output: {"locations":[{"buabList":[{},{},{},{},{}]}]} 输出: {"locations":[{"buabList":[{},{},{},{},{}]}]}

Expected output would be something like: {"locations":[{"buabList":[{"key":"Key-0","value":"Value0"},{"key":"Key-1","value":"Value1"},{"key":"Key-2","value":"Value2"},{"key":"Key-3","value":"Value3"},{"key":"Key-4","value":"Value4"}]}]} 预期输出类似于: {"locations":[{"buabList":[{"key":"Key-0","value":"Value0"},{"key":"Key-1","value":"Value1"},{"key":"Key-2","value":"Value2"},{"key":"Key-3","value":"Value3"},{"key":"Key-4","value":"Value4"}]}]}

Do you might know why GSON is not working as I'd expect it to work? 你可能知道为什么GSON没有工作,因为我期望它工作?

Thanks for any help, highly appreciated! 感谢您的帮助,非常感谢!

The problem you are running into has nothing to do with the TreeSet , but rather with the fact that GSON does not know how to serialize a map Entry in the way that you would like. 您遇到的问题与TreeSet无关,而是GSON不知道如何以您希望的方式序列化地图Entry You therefore need to write a custom serializer for it, which looks something like this: 因此,您需要为它编写自定义序列化程序,如下所示:

public static class EntrySerializer implements JsonSerializer<Entry<String, String>> {
    @Override
    public JsonElement serialize(Entry<String, String> entry, Type typeOfSrc, JsonSerializationContext context) {
        JsonElement serializedKey = context.serialize(entry.getKey());
        JsonElement serializedValue = context.serialize(entry.getValue());

        JsonObject jsonObject = new JsonObject();
        jsonObject.add("key", serializedKey);
        jsonObject.add("value", serializedValue);
        return jsonObject;
    }
}

When you create the Gson object, you then need to register this custom serializer: 创建Gson对象时,需要注册此自定义序列化程序:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(Entry.class, new EntrySerializer())
        .create();

You can read more about custom serializers and deserializers in the GSON documentation . 您可以在GSON文档中阅读有关自定义序列化程序和反序列化程序的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM