简体   繁体   中英

gson.fromJson when json object is inconsistent with java object

Assume I have a class:

class A {
    List<C> b;
}

class C {
    String str;
}

And I have a json string which contains the following:

{ 
    "b": [ 
        { ... },
        { ... }
     ]
}

So doing the following will work just fine:

Gson gson = new Gson();
gson.fromJson(jsonString, A.class);

But now I have a more complex case, where Im using the same json to deliver more data, but I still want to use gson, as its very nice library. So now my json is as follows:

{ 
    "b": [ 
        { ... },
        { ... }
     ],
    "c": 7
}

Is it possible to tell gson object to ignore what it cant evaluate? So It will take only what it knows from my A class, or what I specified using @SerializedName ?

Im aware of the more primitive way, using JSONObject , but for keep using Gson I will have to make "b" nested in one more level for it to work, as it requires an object with an array of objects, and using JSONObject.get("b") will give me only the array within.

UPDATE, to be more specific, I add a json object which I try to work with

This json is what I started with, just an array of b 's, which works fine if I run it:

{
        "b": [
            {
                "str": "first string"
            }
        ]
}

This json is a more complex case where I do have a list of b 's, which is exactly as gson needs, but also another parameter which isnt specific for my A class, which is what I want gson to ignore and behave like the first case.

{
    "b": [
        {
            "str": "first string"
        }
    ],
    "c": 7
}

The way we was always fixing this kind of problem was defining placeholder class, that was able to grab the data, so:

class A {
    List<C> b;
}

class C {
    String str;
}

class ContainerA extends HashMap<String, A>{
}

Then you do:

Gson gson = new Gson();
Map<String, A> javaMap = gson.fromJson(jsonString, ContainerA.class);

This is sort of workaround, but works OK for Gson and Spring for Android with GsonHttpMessageConverter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM