GSON没有正确处理初始化静态列表

时间:2012-04-24 09:03:25

标签: json arraylist gson

如果我这样做:

public static volatile ArrayList<Process> processes = new ArrayList<Process>(){
    {
        add(new Process("News Workflow", "This is the workflow for the news segment", "image"));
    }
};

然后这个:

String jsonResponse = gson.toJson(processes);

jsonResponse为空。

但如果我这样做:

public static volatile ArrayList<Process> processes = new ArrayList<Process>();
processes.add(new Process("nam", "description", "image"));
String jsonResponse = gson.toJson(processes);

Json的回应是:

[{"name":"nam","description":"description","image":"image"}]

为什么?

1 个答案:

答案 0 :(得分:2)

我不知道Gson有什么问题,但是你知道吗,你在这里创建ArrayList的子类?

new ArrayList<Process>(){
    {
        add(new Process("News Workflow", "This is the workflow for the news segment", "image"));
    }
};

您可以通过

进行检查
System.out.println( processes.getClass().getName() );

它不会打印java.util.ArrayList

我认为您希望将静态初始化用作

public static volatile ArrayList<Process> processes = new ArrayList<Process>();
static {
    processes.add( new Process( "News Workflow", "This is the workflow for the news segment", "image" ) );
};

似乎匿名类存在问题,同样的问题在这里

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GSonAnonymTest {

    interface Holder {
        String get();
    }

    static Holder h = new Holder() {
        String s = "value";

        @Override
        public String get() {
            return s;
        }
    };

    public static void main( final String[] args ) {
        final GsonBuilder gb = new GsonBuilder();
        final Gson gson = gb.create();

        System.out.println( "h:" + gson.toJson( h ) );
        System.out.println( h.get() );
    }

}

UPD:查看Gson User Guide - Finer Points with Objects,最后一点“......匿名类,忽略本地类,不包括在序列化或反序列化中......”