“Expected BEGIN_OBJECT but was STRING at line 1 column 1”

前端 未结 14 2429
误落风尘
误落风尘 2020-11-22 01:11

I have this method:

public static Object parseStringToObject(String json) {
    String Object = json;
    Gson gson = new Gson();
    Object objects = gson.f         


        
14条回答
  •  轮回少年
    2020-11-22 01:58

    In my situation, I have a "model", consist of several String parameters, with the exception of one: it is byte array byte[]. Some code snippet:

    String response = args[0].toString();
    Gson gson = new Gson();
    BaseModel responseModel = gson.fromJson(response, BaseModel.class);
    

    The last line above is when the

    java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column
    

    is triggered. Searching through the SO, I realised I need to have some form of Adapter to convert my BaseModel to and fro a JsonObject. Having mixed of String and byte[] in a model does complicate thing. Apparently, Gson don't really like the situation.

    I end up making an Adapter to ensure byte[] is converted to Base64 format. Here is my Adapter class:

    public class ByteArrayToBase64Adapter implements JsonSerializer, JsonDeserializer {
    
        @Override
        public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return Base64.decode(json.getAsString(), Base64.NO_WRAP);
        }
    
        @Override
        public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(Base64.encodeToString(src, Base64.NO_WRAP));
        }
    }
    

    To convert JSONObject to model, I used the following:

    Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64Adapter()).create();
    BaseModel responseModel = customGson.fromJson(response, BaseModel.class);
    

    Similarly, to convert the model to JSONObject, I used the following:

    Gson customGson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64Adapter()).create();
    String responseJSon = customGson.toJson(response);
    

    What the code is doing is basically to push the intended class/object (in this case, byte[] class) through the Adapter whenever it is encountered during the convertion to/fro JSONObject.

提交回复
热议问题