2012-04-24 61 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,最後點「...匿名類和本地類被忽略,不包括在序列化或反序列化...」