0

我被困在这里两天,试图读取存储在 JSONArray 中的 JSONobjects 的值。我使用简单的 JSON,它没有多大帮助!我只能通过类似 jsonstring=JSONArrayName.get(indx); 的方式访问保存 JSONObjects 的 JSONArray 元素。但后来我无法从存储在“jsonstring”字符串中的 JSON 对象中读取值请帮助!请在下面找到我的代码。

ps:我正在使用 $.ajax,我需要存储接收到的值并在我的服务器中处理/使用它

// 这是我的客户端代码 Login.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 
4

1 回答 1

0

我将图书馆改为杰克逊,它工作得非常好。我不得不对我的字符串进行一些调整,我必须删除字符串开头的引号和结尾的引号“{}”然后我必须用空格替换所有存在的 {} 反斜杠以获得有效的字符串格式 { "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();
于 2014-07-14T14:23:31.300 回答