简体   繁体   中英

Gson conversion of a simple string fails with exception

I need to convert a json string to particular type based on the function's return type. The json string could also be a plain string. I am facing issues while converting the strings using gson.fromJson method.

Why is an exception thrown in gson.fromJson if the string contains a space? And how do I get around this?

import java.lang.reflect.Method;

import com.google.gson.Gson;

class Trial {
    Object retu() {
        return "BEVERLY OUTLAW";
    }
}

public class sample {
    public static void main (String args[]) {
        Gson gson = new Gson();
        Trial obj = new Trial();

        Method func = obj.getClass().getDeclaredMethods()[0];
        Object o = gson.fromJson("beverlyoutlaw", func.getGenericReturnType());
        System.out.println(o); ---> this prints beverlyoutlaw
        o = gson.fromJson("beverly outlaw", func.getGenericReturnType()); ---> This throws an exception!
        System.out.println(o);
    }
}

Strings in Json need to be surrounden by quotes. That is - in the Json itself!

Neither "beverlyoutlaw" nor "beverly outlaw" contain quotes in the string - the quotes are just part of the Java String literal.

Apparently Gson does not enforce this for strings without spaces - for strings with spaces however it is strictly necessary.

To fix your issue, use o = gson.fromJson("\"beverly outlaw\"", func.getGenericReturnType());

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