weixin_33686714 2014-06-24 12:29 采纳率: 0%
浏览 121

简单的JSON字符串查询

I am developing a web-app using AJAX requests on the client-side and Servlets on the server-side.

My aim is to send objects of Javascript to server, then do some manipulations there and send it back to show here.

Let's say my js object is

var obj={hero:"Spiderman",name:"Peter Parker"};

My Approach

1.Convert obj to JSON string and send

var str= JSON.stringify(obj);
xmlhttp.open("POST",myurl,true);
xmlhttp.setRequestHeader("Content-Type","application/json",true);
xmlhttp.send("data="+str); 

2. Recieve string,convert this back to JSON, manipulate "name" to "Bruce Wayne" and send it back as string

3.Recieve and convert back to Json

var data= JSON.parse(xmlhttp.responseText);

I am struggling at second point.I am using org.json for it .I searched and read docs but could not find satisfied answer for converting string to json and vica-versa in JAVA in my context.

It would be really helpful one could provide simple working code or point to some links where I can study.

P.S :

I cannot use Jquery as I am using AngularJS. See Why?

I will always send valid JSON string.

I can use other JSON lib. if its good than org.json and satisfy my needs. Please provide its jar download link.

  • 写回答

1条回答 默认 最新

  • weixin_33728268 2014-06-24 12:38
    关注

    Assuming you are able to pull out data in your server code

    This is how you can do it using org.json:

    JSONParser parser = new JSONParser();
    JSONObject requestObj = (JSONObject) parser.parse(data);
    String name = (string)requestObj.get("name");
    name = "Bruce Wayne";
    

    Code to create the response can look something like this:

    JSONObject response = new JSONObject();
    response.put("name",name);
    return response.toJSONString();
    

    This assumes your server method returns a String type

    And in case if you are using Servlet you can use HttpServletResponse object res to create response like:
    res.setContentType("application/json"); OutputStream os = res.getOutputStream(); os.write(response.toString().getBytes()); os.close();

    评论

报告相同问题?