【问题标题】:GSON not handlig initialized static list correctlyGSON 未正确处理初始化静态列表
【发布时间】:2012-04-24 09:03:25
【问题描述】:

如果我这样做:

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

这是为什么呢?

【问题讨论】:

    标签: json arraylist gson


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-24
      • 2022-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多