Can not convert json string to object

霸气de小男生 提交于 2019-12-11 19:28:51

问题


I'm constructiong a JSONObject in my javascript and then sending it as a string to my servlet using this code:

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);
                                           }
                 });
 },

The string looks like: [{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}] and the servlet receives it without a problem.

Then I'm getting this in my 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);
            }

I'm trying to convert the JSON string back to object in the servlet in order to be able to loop trough the items, or to get the needed one. The library I'm using is org.json

I have tired:

JSONObject jsonObj = new JSONObject(step);

Without any success. Just got this error: Unhandled exception type JSONException I don't know what is happening. Maybe I'm too tired already. I'm sure that I'm missing something really small, but I'm unable to spot it.

I know that it has been asked hundreds of times. I know that I will get tons of downvotes, but I was unable to find an answer for my issue.


回答1:


I tried the string you posted in your comment and it works fine. Here is the full code:

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();
        }
    }
}

p.s. I am using org.json-20120521.jar library




回答2:


Here your json String is converted to JSONObject .

In your case its not happening because [] brackets denotes Array. so first it is Array and then {} JSONObject in case of your String.

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();
    }
    }
 }

OUTPUT

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"}


来源:https://stackoverflow.com/questions/17992753/can-not-convert-json-string-to-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!