简体   繁体   中英

Java String to JsonObject returns null

I'm trying to convert String to JSONObject, but always returns null.

At front page, I used $.ajax to send post data,

    var jsonInfo = '{"search_key":"apple", "person":{"name":"test","age":20}}';
    
    var testApi = $.ajax({
        type : "POST", 
        url : "/test/testPerson",
        dataType : "json",
        data : {
            "apiData" : JSON.stringify(jsonInfo)
        }
    })
    .done(function(data, status){
        console.log("success!" + status);
    });

At Servlet, I tried to get the JSONObject with following code:

    JSONObject jsonObject = new JSONObject();
    JSONParser parser = new JSONParser();
    Object obj = null;
    try {
        obj = parser.parse(reqApiKey2);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    jsonObject = (JSONObject) obj;

But I got an error, java.lang.ClassCastException: java.lang.String cannot be cast to org.json.simple.JSONObject at jsonObject = (JSONObject) obj;

I tried to send the data with JSON.parse(jsonInfo) from web, but same result.

Thank you for your advices, and helps.

Your client code is turning the json in the variable jsonInfo into a plain String. Don't do that - it's already JSON!

Change:

data : {
    "apiData" : JSON.stringify(jsonInfo)
}

to:

data : {
    "apiData" : jsonInfo
}

Your server code is correctly deserializing it as String , not an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM