2016-12-18 11 views
-1

オブジェクトに文字列属性をdeserialise -GSONが、私は次のタイプのJSONレスポンスを持っている

{ 
    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

現行のJSでCountryオブジェクトを国別に解析する方法はありますか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); 
} 
関連する問題