get value separately from json object in java servlet

房东的猫 提交于 2019-12-13 08:14:02

问题


this is my javascript code to send json object to servlet

username = "Nash";
password = "619here";
type = "all";
data = '{ "username": "' + username + '", "password": "' + password + '", "type": "' + type + '" }';
request = JSON.parse(data);

$.getJSON(url, request, function (response) {
    $("#result").append("<h1>Success</h1>");
    $.each(response.vehicle, function (no, vehicle) {

        $.each(vehicle, function (key, value) {

            $("#result").append("<h2>" + key + " : " + value + "</h2>");

        });

        $("#result").append("<br>");
    });

})

I want read json object from java servlet and get data separately. like this

String username = username from json object
String password = password from json object
String type = type from json object

I'm using json-lib-2.4-jdk15.jar please help me..


回答1:


In your servlet, do the following in the do[Get,Post]() method

JSONObject jsonObject = JSONObject.fromObject( request.getQueryString() );  

String username= jsonObject.get( "username" );  
String password= jsonObject.get( "password" ); 
String type= jsonObject.get( "type" ); 

You also need the remove the following line from your JS.

request = JSON.parse(data);


来源:https://stackoverflow.com/questions/17002805/get-value-separately-from-json-object-in-java-servlet

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