将Gson转换为Object?

时间:2014-11-19 16:41:06

标签: android json web-services gson

我正在尝试使用Gson来使用Web服务的JSON返回。那就是JSON返回这种格式:

{
  "cod":999,
  "msg":"User Data.",
  "return":{
    "ID":"74",
    "name":"FERNANDO PAIVA",
    "devices":[]
  }
}

当我尝试使用gson.fromJson(json_return, MyObject.class时,它不起作用并抛出异常。 我关注此用户指南:https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson

我该怎么做?

我正在尝试这个。

public class User implements Serializable{
    private static final long serialVersionUID = 1L;

    @SerializedName("ID")
    private Long id;

    private String name;

    //get and set
}

/** get informations of web service */
public static String get(String url){       
        String s = null;

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse httpResponse = httpClient.execute(new HttpGet(url));
            HttpEntity entity = httpResponse.getEntity();
            if(entity != null){
                s = EntityUtils.toString(entity);                           
            }           
        } catch (ClientProtocolException e) {           
            e.printStackTrace();
        } catch (IOException e) {           
            e.printStackTrace();
        } 
        return s;   
    }


/** return object User */    
public User getObjectById(){
    String url = "mydomain.com.br/script.php?email=myemail@domain.com";;
    String response = HttpClient.get(url);
    Gson gson = new Gson();
    ResponseUser ru = gson.fromJson(response, ResponseUser.class);
    User u = ru.getUser();

    return u;
}


public class ResponseUser {

    @SerializedName("return")
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }       
}

例外

11-19 12:56:23.281: E/AndroidRuntime(1481): FATAL EXCEPTION: main
11-19 12:56:23.281: E/AndroidRuntime(1481): Process: br.com.package.myapp, PID: 1481
11-19 12:56:23.281: E/AndroidRuntime(1481): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.package.myapp/br.com.package.myapp.act.MainActivity}: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.os.Handler.dispatchMessage(Handler.java:102)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.os.Looper.loop(Looper.java:136)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.app.ActivityThread.main(ActivityThread.java:5017)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at java.lang.reflect.Method.invokeNative(Native Method)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at java.lang.reflect.Method.invoke(Method.java:515)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at dalvik.system.NativeStart.main(Native Method)
11-19 12:56:23.281: E/AndroidRuntime(1481): Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
11-19 12:56:23.281: E/AndroidRuntime(1481):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at com.google.gson.Gson.fromJson(Gson.java:803)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at com.google.gson.Gson.fromJson(Gson.java:768)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at com.google.gson.Gson.fromJson(Gson.java:717)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at com.google.gson.Gson.fromJson(Gson.java:689)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at br.com.package.myapp.dao.UsuarioDAO.getObjectById(UsuarioDAO.java:46)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at br.com.package.myapp.act.MainActivity.onCreate(MainActivity.java:27)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.app.Activity.performCreate(Activity.java:5231)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
11-19 12:56:23.281: E/AndroidRuntime(1481):     ... 11 more
11-19 12:56:23.281: E/AndroidRuntime(1481): Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
11-19 12:56:23.281: E/AndroidRuntime(1481):     at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
11-19 12:56:23.281: E/AndroidRuntime(1481):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
11-19 12:56:23.281: E/AndroidRuntime(1481):     ... 20 more

2 个答案:

答案 0 :(得分:3)

try {
    JSONObject responseObj = new JSONObject(content);
    Gson gson = new Gson();
    User user = gson.fromJson(responseObj.getJSONObject("return"), User.class);
} catch (JSONException e) {
// catch here               
}

假设用户类设置正确

答案 1 :(得分:1)

第一个问题是,您的User类不代表您从Web服务中获取的JSON,但它只代表响应中的"return"字段...

尝试创建另一个代表JSON响应的类,例如:

public class Response {

    @SerializedName("return")
    private User user;

    // getter & setter
}

然后

response = gson.fromJson(response, Response.class);
u = response.getUser();

除此之外,您必须将id课程中的字段User的类型更改为String
Gson抱怨是因为你告诉它将"ID"解析为Long,这就是expected BEGIN_OBJECT but was a String的原因,因为它找到了值String "74" 1}}