1

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
  • 6,906
  • 5
  • 45
  • 73
Stein Dekker
  • 793
  • 1
  • 6
  • 21

3 Answers3

1

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.

Community
  • 1
  • 1
giampaolo
  • 6,906
  • 5
  • 45
  • 73
0

Refer to this post as per the information provided in the question this should solve your problem Json parsing with Gson with data and arrays

Community
  • 1
  • 1
Ravi
  • 4,872
  • 8
  • 35
  • 46
  • This isn't the thing I was looking for, because I don't need to deserialize a json file with a array property inside the class, but I need to deserialize a json array of the whole class which contains a nested class. – Stein Dekker Sep 21 '13 at 12:11
0

Using gson:

Gson gson = new Gson();
String json = "[{\"b\" : {\"a\": \"Hello!\"}}, {\"b\" : {\"a\": \"Hi!\"}}, {\"b\" : {\"a\": \"Hello2!\"}}]";
A[] arrA = new A[0];
System.out.println(Arrays.toString(gson.fromJson(json, arrA.getClass())));
anubhava
  • 761,203
  • 64
  • 569
  • 643