GSON:使用java.util.TreeSet序列化对象 [英] GSON: Serialize object with java.util.TreeSet

查看:293
本文介绍了GSON:使用java.util.TreeSet序列化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何正确地序列化TreeSet?为了让你知道什么是不工作的,我已经建立了这个小演示项目。主要目标是打印我的QData对象的JSON字符串。



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;
$ b $ public class App
{
public static void main(String [] args)
{
QData qdata = new QData();

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

LData l =新的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>> sortedBuBuList = 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

  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(){
返回位置;
}

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


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

}

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

}

输出: {locations:[{buabList:[{},{},{},{},{}]}]}



预期的输出将如下所示: {locations:[{buabList:[{key:Key-0,value:Value0},{ 钥匙: KEY-1, 值: 值1},{ 钥匙: KEY-2, 值: 值2},{ 钥匙: KEY-3, value:Value3},{key:Key-4,value:Value4}]}]}



您是否知道为什么GSON不能像我预期的那样工作?



感谢您的帮助,非常感谢!

解决方案

您遇到的问题与 TreeSet 无关,而是与GSON不知道如何以你喜欢的方式序列化地图 Entry 。因此,您需要为它编写一个自定义序列化器,它看起来像这样:

  public static class EntrySerializer实现了JsonSerializer< Entry<字符串,字符串>> {
@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);
返回jsonObject;




$ b当你创建 Gson时对象,然后你需要注册这个自定义的序列化程序:

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

您可以在 GSON文档


How can I serialize a TreeSet properly? 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.

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

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

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":[{},{},{},{},{}]}]}

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"}]}]}

Do you might know why GSON is not working as I'd expect it to work?

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. 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 = new GsonBuilder()
        .registerTypeAdapter(Entry.class, new EntrySerializer())
        .create();

You can read more about custom serializers and deserializers in the GSON documentation.

这篇关于GSON:使用java.util.TreeSet序列化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆