2012-04-24 66 views
0

handlig初始化静态列表如果我这样做: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"}] 

这是为什么?

回答

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