简体   繁体   中英

gson de-serialization to string in java

In my project I'm using gson. I have a problem when I want to de-serialize a json sub object form my class to a String for example

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. 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.
Thanks

You can try to register a custom TypeAdapter for the String and fix it.

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

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

Javadoc User Guide

The following code works just fine. Not really sure if that's the Json structure your are trying to parse though.

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:

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

Note the single quoutes around the Stringx value.

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