【问题标题】:Can not convert json string to object无法将json字符串转换为对象
【发布时间】:2013-08-02 07:10:48
【问题描述】:

我正在我的 javascript 中构建一个 JSONObject,然后使用以下代码将其作为字符串发送到我的 servlet:

insertDtls = function() {
                    var jsonObj = [];
                    jsonObj.push({location: this.location()});
                    jsonObj.push({value: this.value()});
                    jsonObj.push({coverage: this.coverage()});
                    jsonObj.push({validPeriod: this.collateralValidPer()});
                    jsonObj.push({description: this.description()});

                    var b = JSON.stringify(jsonObj);
                    console.log(b.toString());

                     $.ajax({
                             url:"/HDSWFHub/AppProxy",
                             type: 'GET',
                             data: $.extend({WrJOB: "insertDtls", mainData: b}, tJS.getCommonPostData()),
                             dataType: "json",
                             success: function(responseText, status, xhr){
                                               updateViewModel(responseText);
                                           },
                             error: function(jqXHR, textStatus, error){
                                               tJS.manageError(jqXHR);
                                           }
                 });
 },

字符串看起来像: [{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}] 并且 servlet 接收它没有问题。

然后我在我的 servlet 中得到这个:

String step = request.getParameter("mainData");

            JSONObject jsonObj = new JSONObject();
            final JSONObject obj = new JSONObject();
            System.out.println(step);
            try {
                obj.put("viewModel", "index");
                obj.put("WrSESSIONTICKET", sessionTicket);
                response.getWriter().print(obj.toString());
            } catch (final Exception e) {
                logException(request, response, e, true);
            }

我正在尝试将 JSON 字符串转换回 servlet 中的对象,以便能够循环遍历项目或获取所需的项目。我使用的库是org.json

我累了:

JSONObject jsonObj = new JSONObject(step);

没有任何成功。刚收到这个错误: Unhandled exception type JSONException 我不知道发生了什么。也许我已经太累了。我确定我遗漏了一些非常小的东西,但我无法发现它。

我知道它已被问过数百次。我知道我会得到大量的反对票,但我无法找到我的问题的答案。

【问题讨论】:

  • 你说你试过JSONObject jsonObj = new JSONObject(step);,但我在代码中没有看到它!
  • 因为它不起作用。 :) 这是错误:Unhandled exception type JSONException
  • 打印出servlet中的变量step,看看它是否是一个正确的JSON字符串。请发布它,以便我们都可以查看它;)
  • 这里是:[{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}]
  • 事实上,我注意到你的字符串中有一些东西...2013 特别是零和一不是 ascii 字符...这可能是问题的原因。

标签: java json servlets org.json


【解决方案1】:

我尝试了您在评论中发布的字符串,它工作正常。完整代码如下:

import org.json.JSONArray;
import org.json.JSONException;

public class jsonArray {
    public static void main(String[] args) {
        String text = "[{\"location\":\"Boston\"},{\"value\":\"5\"},{\"coverage\":\"15\"},{\"validPeriod\":\"08/05/2013\"},{\"description\":\"test description\"}]";

        try {
            JSONArray jsonArray = new JSONArray(text);
            System.out.println(jsonArray.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

附言我正在使用 org.json-20120521.jar 库

【讨论】:

  • 很好,但你逃脱了一些东西。我在 ajax 的帮助下从 javascript 中获取字符串。
  • 在try {...} catch (JSONException e) {... }中添加你的json代码
  • 好的,我想通了。我无法相信我的大脑被卡住了。谢谢你帮助我!!!
【解决方案2】:

这里你的 json String 被转换为 JSONObject 。

在您的情况下它不会发生,因为 [] 括号表示数组。所以首先是数组,然后是 {} JSONObject 以防你的字符串。

import org.json.JSONArray;
import org.json.JSONObject;

public class Test {

    static String str = "[{\"location\":\"Boston\"},{\"value\":\"5\"},{\"coverage\":\"15\"},{\"validPeriod\":\"08/05/2013\"},{\"description\":\"test description\"}]";

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
        JSONArray jsonArr = new JSONArray(str);
        System.out.println("JSON ARRAY IS : ");
        System.out.println(jsonArr.toString());
            for(int i =0 ; i<jsonArr.length() ;i++ ){
                JSONObject jsonObj = jsonArr.getJSONObject(i);
                System.out.println();
                System.out.println(i+" JSON OBJECT IS : ");
                System.out.println(jsonObj.toString());

            }
    } catch (org.json.JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
 }

输出

JSON ARRAY IS : 
[{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}]

0 JSON OBJECT IS : 
{"location":"Boston"}

1 JSON OBJECT IS : 
{"value":"5"}

2 JSON OBJECT IS : 
{"coverage":"15"}

3 JSON OBJECT IS : 
{"validPeriod":"08/05/2013"}

4 JSON OBJECT IS : 
{"description":"test description"}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 2021-08-01
    • 2022-12-09
    相关资源
    最近更新 更多