简体   繁体   English

gson反序列化到Java中的字符串

[英]gson de-serialization to string in java

In my project I'm using gson. 在我的项目中,我正在使用gson。 I have a problem when I want to de-serialize a json sub object form my class to a String for example 当我想将我的类的json子对象反序列化为String时遇到问题

Class X
{
    Object1 x1 // expected json -> '{"param1": "pvalue", "param2":"pvalue"}'
    Object2 x2 //expected json -> '{"param1": "pvalue", "param2":"pvalue"}'
    String x3 //expected json ->'{"param1": "pvalue", "param2":"pvalue"}'
}

Gson can't de-serialize x3 since it's contents is json object but I need it as a string and not as a Java object. Gson无法反序列化x3,因为它的内容是json对象,但我需要它作为字符串而不是Java对象。 Class X { Object1 x1 // expected json -> '{"param1": "pvalue", "param2":"pvalue"}' Object2 x2 //expected json -> '{"param1": "pvalue", "param2":"pvalue"}' String x3 //expected json ->'{"param1": "pvalue", "param2":"pvalue"}' } How do I save the contents of x3 in a String and not as a object. 类X {Object1 x1 //期望的json->'{“ param1”:“ pvalue”,“ param2”:“ pvalue”}'Object2 x2 //期望的json->'{“ param1”:“ pvalue”,“ param2 “:” pvalue“}'字符串x3 //期望的json->'{” param1“:” pvalue“,” param2“:” pvalue“}'}}如何将x3的内容保存在字符串中而不是宾语。
Thanks 谢谢

You can try to register a custom TypeAdapter for the String and fix it. 您可以尝试为字符串注册自定义TypeAdapter并对其进行修复。

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(String.class, new MyTypeAdapter());

Gson gson = gsonBuilder.create();
....

Javadoc User Guide Javadoc 用户指南

The following code works just fine. 以下代码可以正常工作。 Not really sure if that's the Json structure your are trying to parse though. 不确定是否要尝试解析的是Json结构。

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

        Response response = gson.fromJson( THE_JSON, Response.class );

        System.out.println( response.object1 );
        System.out.println( response.object1 );
        System.out.println( response.stringx );
    }

    class Response
    {
        @SerializedName("Objectx1")
        Objectx object1;

        @SerializedName("Objectx2")
        Objectx object2;

        @SerializedName("Stringx")
        String stringx;

        class Objectx
        {
            @SerializedName("param1")
            String param1;

            @SerializedName("param2")
            String param2;
        }
    }
}

And THE_JSON is: 而THE_JSON是:

{
    "Objectx1": {
        "param1": "value1",
        "param2": "value2"
    },
    "Objectx2": {
        "param1": "value3",
        "param2": "value4"
    },
    "Stringx": '{
        "param3": "value3",
        "param4": "value4"
    }'
}

Note the single quoutes around the Stringx value. 请注意在Stringx值周围的单仲裁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM