James Raitsev
James Raitsev

Reputation: 96391

Trouble deserializing json file via gson

I have a json file

{
    "l": {
        "default_level": "...",
        "impl": "...",
        "levels": [
            ...,
            ...
        ]
    },
    "a": [
        {
            "format": "...",
            "filename": "...",
            "rotation": "...",
            "ls": [
                ...,
                ...
            ]
        }
    ]
}

Which i am trying to map to

public class ABC {

    private List<A> aList = new ArrayList<>();
    private L lConfig = new L();

    // Gettters and Setters for aList and l

    public static class L {
        String default_level;
        String impl;

        List<String> levels = new ArrayList<>();

        // Gettters and Setters

        @Override
        public String toString() {
            // ...
        }
    }

    public static class A {
        String format;
        String filename;
        String rotation;

        List<String> ls = new ArrayList<>();

        // Getters and Setters

        @Override
        public String toString() {
            // ...
        }
    }
}

which is being deserialized by

public static BLAH load(String externalConfigFile) throws IOException {
    ABC config = null;

    Path path = Paths.get(externalConfigFile);
    if (Files.exists(path) || Files.isReadable(path)) {
        config = new Gson().fromJson(readFile(externalConfigFile), ABC.class);
    }

    return config;
}

Which, upon printing gives me

A[] 
L{default_level='null', impl='null', levels=[]}

Why is stuff not set?

Upvotes: 0

Views: 243

Answers (2)

MikO
MikO

Reputation: 18741

I think the problem is just the names of the attributes. In Gson, attributes' names must match the fields' names in the JSON.

So, you need to change the names of the attributes in the ABC class. Something like:

public class ABC {

    private List<A> a;
    private L l;

    //All the rest is okay...
}

Otherwise, you should use the annotation @SerializedName, like this:

@SerializedName("a")
private List<A> aList;
@SerializedName("l")
private L lConfig;

Upvotes: 2

Csaba
Csaba

Reputation: 340

Try using an array instead of a list here:

private A[] aList = {};

The List<A> will lose it's <A> during runtime and gson won't know where it should map the JSON array you're providing it.

Upvotes: 0

Related Questions