How to convert a String to JsonObject using gson library

后端 未结 9 1290
既然无缘
既然无缘 2020-11-30 23:45

Please advice how to convert a String to JsonObject using gson library.

What I unsuccesfully do:

String stri         


        
9条回答
  •  旧巷少年郎
    2020-12-01 00:26

    You don't need to use JsonObject. You should be using Gson to convert to/from JSON strings and your own Java objects.

    See the Gson User Guide:

    (Serialization)

    Gson gson = new Gson();
    gson.toJson(1);                   // prints 1
    gson.toJson("abcd");              // prints "abcd"
    gson.toJson(new Long(10));        // prints 10
    int[] values = { 1 };
    gson.toJson(values);              // prints [1]
    

    (Deserialization)

    int one = gson.fromJson("1", int.class);
    Integer one = gson.fromJson("1", Integer.class);
    Long one = gson.fromJson("1", Long.class);
    Boolean false = gson.fromJson("false", Boolean.class);
    String str = gson.fromJson("\"abc\"", String.class);
    String anotherStr = gson.fromJson("[\"abc\"]", String.class)
    

提交回复
热议问题