JSON string from Gson: remove double quotes

前端 未结 3 947
悲&欢浪女
悲&欢浪女 2020-12-30 19:28

Here is an example of my Json code:

array(\"id\" => 0, \"navn\" => \"Vind telefon\", \"udgiver\" => \"Telia\", \"beskrivelse\" => utf8_encode(\"V         


        
相关标签:
3条回答
  • 2020-12-30 20:05
    public class StringTypeSerializationAdapter extends TypeAdapter<String> {
    
    
    public String read(JsonReader reader) {
        throw new UnsupportedOperationException();
    }
    
    public void write(JsonWriter writer, String value) throws IOException {
        if (value == null) {
            writer.nullValue();
            return;
        }
        writer.jsonValue(value);
    }
    }
    

    above will help you removing double quotes across strings. this is using GSON library

    0 讨论(0)
  • 2020-12-30 20:19

    It's not documented properly, but JsonElement#toString() gets you a string that represents the JSON element and would be appropriate for re-creating the JSON serialization. What you want is JsonElement#getAsString(). This will throw an error if you're not looking at a string, but if you are, you'll get the string value.

    Here's a test program to demonstrate:

    import com.google.gson.JsonElement;
    import com.google.gson.JsonParser;
    public class Test {
        public static void main(String[] args) {
            String in = "{\"hello\":\"world\"}";
            System.out.println(in);
            JsonElement root = new JsonParser().parse(in);
            System.out.println(root.getAsJsonObject().get("hello").toString());
            System.out.println(root.getAsJsonObject().get("hello").getAsString());
        }
    }
    

    And its output:

    {"hello":"world"}
    "world"
    world
    
    0 讨论(0)
  • 2020-12-30 20:28

    To put object or array properties into your JsonObject and get them back as objects and arrays (not as string), use the approach:

    new JsonObject().add(
      "mySubobject",
      new Gson().toJsonTree(
        new JsonObject()));
    
    0 讨论(0)
提交回复
热议问题