有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Servlet(JAVA)中JSON数组中JSON对象的ajax访问值

我在这里呆了两天,试图读取存储在JSONArray中的JSONObject的值。我使用JSON很简单,它没有帮助很多!我只能通过像这样的jsonstring=JSONArrayName来访问保存JSONObject的JSONArray元素。get(indx);但是我无法从存储在“jsonstring”字符串中的JSON对象中读取值。请帮助!!请在下面找到我的代码

附言:我用的是美元。ajax,我需要存储接收到的值并在服务器中处理/使用它

//这是我的客户端代码登录。html


//My servlet code to process json received from client 
BufferedReader reader = request.getReader();
StringBuilder myinputholder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
    myinputholder.append(line);
}

Object obj = JSONValue.parse(myinputholder.toString());
JSONArray newjsonarr = (JSONArray) obj;
     //  JSONObject newjson= (JSONObject) newjsonarr.get(0); // this line causes errors 
PrintWriter pw = response.getWriter();
String f = JSONValue.toJSONString(newjsonarr.get(0));// this will give me a json object 
         // proper format but I cant do anything with the values inside

JSONValue.writeJSONString(f, pw); // this is only for troubleshooting 

共 (1) 个答案

  1. # 1 楼答案

    我把图书馆改成了Jackson,效果非常好。 我必须对字符串进行一些调整,我必须删除字符串开头的引号和“{}”结尾的引号,然后我必须用空格替换所有存在的{}反斜杠,以获得有效的字符串格式{“Key”:“Value”,“Key”:,“Value”},因为我的字符串看起来像“{“Key\”:“Value\”,“Key\:,“Value\”}”。我可以提取从客户端发送的每个密钥的每个值。 找到下面的代码

        String uname="";
        String pass="";
        BufferedReader reader = request.getReader();
        StringBuilder myinputholder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            myinputholder.append(line);
        }
    
        Integer s= myinputholder.length();
    
        String ss= myinputholder.toString();
        String sss= ss.substring(1, s-1); // this is to avoid the beginning and end "{}"
        sss=sss.replace("\\", ""); \\ this line is to replace all \ with space
        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getJsonFactory();
        JsonParser jp = factory.createJsonParser(sss);
        JsonNode actualObj = mapper.readTree(jp);
        JsonNode subnode= actualObj.path("username");
        JsonNode subnode2= actualObj.path("password");
        uname= subnode.getTextValue();
        pass=actualObj.get("password").getTextValue();