0

如果我这样做:

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

这是为什么?

4

1 回答 1

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,最后一点“......匿名类和本地类被忽略且不包含在序列化或反序列化中......”

于 2012-04-24T12:18:12.120 回答