How to deserialize a JSON file into an ArrayList with nested classes?

Stein Dekker

I have this Java class:

class A {
    private B b;

    class B {
        private String a;
        //getter + setter
    }    
}

This is the content of JSON file:

[{"b" : {"a": "Hello!"}},
 {"b" : {"a": "Hi!"}},
 {"b" : {"a": "Hello2!"}}]

I want to deserialize my JSON file into an ArrayList<A> with the nested class inside. How can I do this?

giampaolo

You can simply achieve this with Gson.

package stackoverflow.questions.q18932252;

import java.lang.reflect.Type;
import java.util.*;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Q18932252 {

    public static void main(String[] args){
        String json = "[{\"b\" : {\"a\": \"Hello!\"}}, {\"b\" : {\"a\": \"Hi!\"}}, {\"b\" : {\"a\": \"Hello2!\"}}]";
        Type listOfA = new TypeToken<List<A>>() {}.getType();
        Gson g = new Gson();
        ArrayList<A> result = g.fromJson(json, listOfA);
        System.out.println(result);


    }

}

With this result (I have added standard toString methods):

[A [b=B [a=Hello!]], A [b=B [a=Hi!]], A [b=B [a=Hello2!]]]

Since you are asking about a JSON file, ie a text file that contains a JSON string, please make reference to How to create a Java String from the contents of a file question for loading a file into a string.

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Deserialize nested JSON into C# objects

来自分类Dev

How to calculate length of nested JSON?

来自分类Dev

Cannot deserialize Json to object

来自分类Dev

Why the unexpected naming of nested classes in Python? How to "fix"?

来自分类Dev

How to Read JSON File

来自分类Dev

How to parse nested JSON data structure

来自分类Dev

How to bind json nested object in Jquery Jtable?

来自分类Dev

Java HashMap with nested String or ArrayList

来自分类Dev

没有来自Json Deserialize的结果

来自分类Dev

C#Json Deserialize返回null

来自分类Dev

Json Multiset vs ArrayList

来自分类Dev

从JSON对象创建ArrayList

来自分类Dev

从 Arraylist 创建 JSON

来自分类Dev

How to parse values from a JSON file in Python

来自分类Dev

How to format JSON data when writing to a file

来自分类Dev

Parsing nested values in JSON

来自分类Dev

How to serialize/deserialize using illinois-edison

来自分类Dev

合并json并创建arraylist <object>

来自分类Dev

将arraylist转换为JSON

来自分类Dev

如何从 Arraylist 值创建 Json?

来自分类Dev

Android how to savestate arraylist

来自分类Dev

Newtonsoft Json Deserialize Dictionary作为DataContractJsonSerializer的键/值列表

来自分类Dev

Json.Deserialize在iOS上不起作用

来自分类Dev

使用.NET deserialize()和嵌套的“列表”进行JSON解析

来自分类Dev

JSInterop.Json.Deserialize从DateTime对象丢失了毫秒

来自分类Dev

使用.NET deserialize()和嵌套的“列表”进行JSON解析

来自分类Dev

C#Json.Deserialize与带有子类的带接口的对象

来自分类Dev

带有对象问题的 Arraylist 中的 Firebase JSON 到 Arraylist

来自分类Dev

How do I do a nested list (array) of schema references in json schema