2016-12-18 35 views
-1

我有以下类型的JSON响应 -GSON deserialise一个字符串属性为对象

{ 
    userName:"Jon Doe", 
    country:"Australia" 
} 

我的User类看起来是这样的 -

public class User{ 
    private String userName; 
    private Country country; 
} 

GSON解析失败,出现以下错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 3 column 18 path $[0].country

有什么办法可以告诉GSON解析国家与国家对象与我目前的JS ON响应?

+0

[试试这个?](http://stackoverflow.com/a/18483355/1398531) –

+0

什么是国家?一个类还是一个枚举? – roby

+0

@roby国家是一个类。 –

回答

1

您可以通过注册一个自定义解串器来实现这一点。

public static class Country { 
    private String name; 

    public Country(String name) { 
     this.name = name; 
    } 

    @Override 
    public String toString() { 
     return "Country{" + "name='" + name + '\'' + '}'; 
    } 
} 

public static class Holder { 

    private String x; 
    private Country y; 

    public Holder() { 
    } 

    public void setX(String x) { 
     this.x = x; 
    } 

    public void setY(Country y) { 
     this.y = y; 
    } 

    @Override 
    public String toString() { 
     return "Holder{" + "x='" + x + '\'' + ", y=" + y + '}'; 
    } 
} 


@Test 
public void test() { 
    GsonBuilder gson = new GsonBuilder(); 
    gson.registerTypeAdapter(Country.class, (JsonDeserializer) (json, typeOfT, context) -> { 
     if (!json.isJsonPrimitive() || !json.getAsJsonPrimitive().isString()) { 
      throw new JsonParseException("I only parse strings"); 
     } 
     return new Country(json.getAsString()); 
    }); 
    Holder holder = gson.create().fromJson("{'x':'a','y':'New Zealand'}", Holder.class); 
    //prints Holder{x='a', y=Country{name='New Zealand'}} 
    System.out.println(holder); 
} 
相关问题