【问题标题】:Attempting to create JSONObject from String with Java (Android Studio)尝试使用 Java (Android Studio) 从 String 创建 JSONObject
【发布时间】:2019-06-01 09:49:57
【问题描述】:

我遇到了一个问题,我尝试将序列化的 json 字符串解析为 JSONObject,以便稍后检索另一个对象 PetFedInfo 的键值。我从我的 android 应用程序调用到 ASP.NET Web API,字符串成功返回。

这是我从 asp.net api 服务器解析结果的代码:

    JSONObject jsonObj = new JSONObject();
    try {

        String stringFromServer =  PostHTTP(Constants.POST_PET_GETFEDINFO,jObj);
        Log.v("stringFromServer",stringFromServer);
        Log.v("directCallResult",PostHTTP(Constants.POST_PET_GETFEDINFO,jObj));
        Log.v("actualString","{\"petName\":\"nn\",\"lastFedTime\":\"\"}");

        jsonObj = new JSONObject("{\"petName\":\"nn\",\"lastFedTime\":\"\"}");
        Log.v("jsonObjFromManualString",jsonObj.toString());
        jsonObj = new JSONObject(PostHTTP(Constants.POST_PET_GETFEDINFO,jObj));
        Log.v("jsonObjFromDirectCall",jsonObj.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }

在我以调试模式运行应用程序后,实例“stringFromServer”(记录为“stringFromServer”)中的字符串在我尝试创建 JSONObject 时抛出错误:

org.json.JSONException: Value {"petName":"mm","lastFedTime":""} of type java.lang.String cannot be converted to JSONObject
        at org.json.JSON.typeMismatch(JSON.java:112)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:168)
        at org.json.JSONObject.<init>(JSONObject.java:181)
        at com.FeedMyPet.helper.WebRequestManager$2.run(WebRequestManager.java:102)

而我手动输入的字符串(记录为“实际字符串”)成功创建了 JSON 对象。我已经使用 Log.v 将所有字符串值打印到控制台,它们几乎具有相同的输出

V/stringFromServer: "{\"petName\":\"v\",\"lastFedTime\":\"\"}"
V/directCallResult: "{\"petName\":\"v\",\"lastFedTime\":\"\"}"
V/actualString: {"petName":"nn","lastFedTime":""}

我已经查看了 JSONObject 的构造,它接受一个字符串:

    public JSONObject(String json) throws JSONException {
        this(new JSONTokener(json));
    }

我有点迷茫为什么使用引号的序列化对象(没有对象?)成功创建对象,而字符串实例不能。如何让 String 对象与 'actualString' 的结果相匹配?

有人可以指点我正确的方向吗?

【问题讨论】:

  • jsonObj.put(key, value);
  • 这不是我所要求的答案。我在通过构造函数字符串生成 JSONObject 时遇到问题。

标签: java android json


【解决方案1】:

尝试清理从服务器接收到的字符串。可能添加了一些隐藏字符。

你看看这个链接https://stackoverflow.com/a/15469907/578855

你也可以尝试用这个替换双引号

json=json.replace("\\\"","'");

【讨论】:

  • 您好,是的,我已经尝试过了。我试过:code String stringFromServer = PostHTTP(Constants.POST_PET_GETFEDINFO,jObj); jsonObj = new JSONObject(stringFromServer.substring(stringFromServer.indexOf("{"), stringFromServer.lastIndexOf("}") + 1)); code 并得到这个: W/System.err: org.json.JSONException: Expected literal value at character 1 of {\"petName\":\"vv\",\"lastFedTime\":\"\"}
猜你喜欢
  • 2015-03-16
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多