The de-initialization of sometimes a string, and sometimes an object with Gson

I need to parse this JSON data type for java objects:

{"id": 1, "blob": "example text"} 
{"id": 2, "blob": {"to": 1234, "from": 4321, "name": "My_Name"}}

I use Gson and don’t know how to get around this particular problem, "blob" is sometimes a string, and sometimes an object.

+4
source share
3 answers

One solution to your problem is to write TypeAdapterto your class, however, if there are only such cases in your example, you can achieve the same result by letting Gson do the work for you using the most common class you can deserialize.

What I mean is shown in the code below.

package stackoverflow.questions.q19478087;

import com.google.gson.Gson;

public class Q19478087 {

    public class Test {
        public int id;
        public Object blob;
        @Override
        public String toString() {
            return "Test [id=" + id + ", blob=" + blob + "]";
        }


    }

    public static void main(String[] str){
        String json1 = "{\"id\": 1, \"blob\": \"example text\"}";
        String json2 = "{\"id\": 2, \"blob\": {\"to\": 1234, \"from\": 4321, \"name\": \"My_Name\"}}";

        Gson g = new Gson();
        Test test1 = g.fromJson(json1, Test.class);
        System.out.println("Test 1: "+ test1);

        Test test2 = g.fromJson(json2, Test.class);
        System.out.println("Test 2: "+ test2);
    }

}

and this is my execution:

Test 1: Test [id=1, blob=example text]
Test 2: Test [id=2, blob={to=1234.0, from=4321.0, name=My_Name}]

blob LinkedTreeMap, , ((Map) test2.blob).get("to"), :

, .

+3

POJO

class FromToName{
    String to;
    String from;
    String name;
    @Override
    public String toString() {
        return "FromToName [to=" + to + ", from=" + from + ", name=" + name
                + "]";
    }
}

  String json ="{\"id\": 1, \"blob\": \"example text\"}"; 
  //String json = "{\"id\": 2, \"blob\": {\"to\": 1234, \"from\": 4321, \"name\": \"My_Name\"}}";
  Gson gson = new Gson();
  JsonElement element = gson.fromJson (json, JsonElement.class);
  JsonObject jsonObj = element.getAsJsonObject();
  JsonElement id = jsonObj.get("id");
  System.out.println(id);
  if(jsonObj.get("blob") instanceof  JsonPrimitive  ){
         JsonElement blob = jsonObj.get("blob");
         System.out.println(blob);
   }else{
          FromToName blob = gson.fromJson (jsonObj.get("blob"), FromToName.class);
          System.out.println(blob);
   }

- ,

0

Take this as a JSON element, and then use isMethods () to figure out the type at runtime.

Documentation

        JsonParser jp = new JsonParser();
        JsonElement ele = jp.parse(jsonString).getAsJsonObject().get("blob");;

            if (ele.isJsonObject()) {
                  //do related stuff here
            } else if (ele.isJsonArray()) {
                  //do related stuff here
            }
0
source

All Articles