2016-12-18 51 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); 
} 
相關問題