在android上使用gson解析json时出错

时间:2013-07-04 12:31:49

标签: android gson

我正在关注gson-android的这个教程

http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html

我的json是

{"IsAuthenticated":true,"BusinessId":57,"Success":true,"ErrorId":0}

我创建了我的模型对象:

LoginResponse.java

import com.google.gson.annotations.SerializedName;
import com.xxxx.xxxx.R.string;

public class LoginResponse {

    @SerializedName("Sucess")
    private Boolean sucess;

    @SerializedName("IsAuthenticated")
    private Boolean isAuthenticated;

    @SerializedName("BusinessId")
    private String businessId;

    @SerializedName("ErrorId")
    private string errorId;

    public Boolean getSucess() {
        return sucess;
    }

    public void setSucess(Boolean sucess) {
        this.sucess = sucess;
    }

    public Boolean getIsAuthenticated() {
        return isAuthenticated;
    }

    public void setIsAuthenticated(Boolean isAuthenticated) {
        this.isAuthenticated = isAuthenticated;
    }

    public String getBusinessId() {
        return businessId;
    }

    public void setBusinessId(String businessId) {
        this.businessId = businessId;
    }

    public string getErrorId() {
        return errorId;
    }

    public void setErrorId(string errorId) {
        this.errorId = errorId;
    }

}

运行此代码后,我的应用程序正在关闭。

logcat的

    07-04 12:22:40.682: E/AndroidRuntime(2694): FATAL EXCEPTION: AsyncTask #3
07-04 12:22:40.682: E/AndroidRuntime(2694): java.lang.RuntimeException: An error occured while executing doInBackground()
07-04 12:22:40.682: E/AndroidRuntime(2694):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at java.lang.Thread.run(Thread.java:856)
07-04 12:22:40.682: E/AndroidRuntime(2694): Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 67
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.google.gson.Gson.fromJson(Gson.java:803)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.google.gson.Gson.fromJson(Gson.java:741)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.example.xxxx.loginActivity.ValidateUser(LoginActivity.java:300)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.example.xxxx.loginActivity.access$0(LoginActivity.java:276)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.example.xxxx.loginActivity$UserLoginTask.doInBackground(LoginActivity.java:222)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.example.xxxx.loginActivity$UserLoginTask.doInBackground(LoginActivity.java:1)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-04 12:22:40.682: E/AndroidRuntime(2694):     ... 4 more
07-04 12:22:40.682: E/AndroidRuntime(2694): Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 67
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:374)
07-04 12:22:40.682: E/AndroidRuntime(2694):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
07-04 12:22:40.682: E/AndroidRuntime(2694):     ... 14 more

..这就是我这样做的方式

    HttpResponse response = client.execute(httpGet);

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(content));


        Gson gson = new Gson();
        LoginResponse myResponse = gson.fromJson(reader, LoginResponse.class);
        Log.d(TAG, myResponse.getBusinessId().toString());



    } else {
        Log.e(TAG, "Failed to download file");
    }

我做错了吗?我只是跟着啧啧中的东西。任何人都可以帮助我。

更新

在将字符串更改为字符串和其他内容后,我能够修复应用程序崩溃。我仍然无法得到这个对象。

此处更新的日志

07-08 05:02:53.625: W/System.err(869): org.json.JSONException: End of input at character 0 of 
07-08 05:02:53.656: W/System.err(869):  at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
07-08 05:02:53.656: W/System.err(869):  at org.json.JSONTokener.nextValue(JSONTokener.java:97)
07-08 05:02:53.656: W/System.err(869):  at org.json.JSONObject.<init>(JSONObject.java:154)
07-08 05:02:53.656: W/System.err(869):  at org.json.JSONObject.<init>(JSONObject.java:171)
07-08 05:02:53.656: W/System.err(869):  at com.example.xxxx.LoginActivity$UserLoginTask.onPostExecute(LoginActivity.java:238)
07-08 05:02:53.656: W/System.err(869):  at com.example.xxxx.LoginActivity$UserLoginTask.onPostExecute(LoginActivity.java:1)
07-08 05:02:53.656: W/System.err(869):  at android.os.AsyncTask.finish(AsyncTask.java:631)
07-08 05:02:53.656: W/System.err(869):  at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-08 05:02:53.656: W/System.err(869):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-08 05:02:53.675: W/System.err(869):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-08 05:02:53.675: W/System.err(869):  at android.os.Looper.loop(Looper.java:137)
07-08 05:02:53.675: W/System.err(869):  at android.app.ActivityThread.main(ActivityThread.java:5041)
07-08 05:02:53.675: W/System.err(869):  at java.lang.reflect.Method.invokeNative(Native Method)
07-08 05:02:53.675: W/System.err(869):  at java.lang.reflect.Method.invoke(Method.java:511)
07-08 05:02:53.675: W/System.err(869):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-08 05:02:53.675: W/System.err(869):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-08 05:02:53.675: W/System.err(869):  at dalvik.system.NativeStart.main(Native Method)

我用谷歌搜索了这个,但没有得到解决方案

4 个答案:

答案 0 :(得分:1)

   @SerializedName("BusinessId")
    private String businessId;

    @SerializedName("ErrorId")
    private string errorId;

应为整数

  @SerializedName("BusinessId")
    private int businessId;

    @SerializedName("ErrorId")
    private int errorId;

答案 1 :(得分:0)

您的LoginResponse.java中有一个拼写错误:

@SerializedName("Sucess")

应该是

@SerializedName("Success")

也许还有更多的问题,你能检查一下你试图解析的JSON确实是你期望的吗?

答案 2 :(得分:0)

private string errorId;真的是小写吗?您可能需要Stringint(两者都有效)。

gson中的反射内容会读取您的字段类型,并认为它必须是嵌套的json对象可以映射到的对象。可以解释一下Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 67:你的反射映射器期待java.lang.String的一个对象(但不是ErrorId)类型,因为你已经给它了一些它认为是另一种对象 - 神秘的{{1 }}。但是,string是一个知道如何处理的课程。

答案 3 :(得分:0)

您从Gson收到的错误告诉您,它希望在您的JSON中的第67列(字符)中找到{。这意味着errorId是Java类中的对象类型,而不是数字(例如intlong)或String(请参阅下面有关自动{{1}的最后一段转换)。

查看您的代码,您有......

String

显然你已经创建了一个@SerializedName("ErrorId") private string errorId; 类(小写string),使用过它,而Gson正在尝试反序列化它。这就是为什么你从不那样做的原因。首先,类是Java应该以大写字母开头。其次,你永远不应该创建与系统名称相同的类。 (选项B将是您显示的Java类不是实际运行的内容,并且还有其他一些对象类型)。

如果您通过将其更改为s来解决问题,则错误将消失。尽管String(和errorId)现在是Java中的businessId,但Gson实际上会自动将JSON中的数字类型转换为Java类中的String类型。您还需要修复String中的拼写错误,否则它将最终成为sucess,因为JSON中不存在该错误,Gson会默默地忽略任何缺少的元素。