[英]Access values of JSON objects from a JSON array in Servlet (JAVA)
我在这里停留了两天,试图读取存储在JSONArray中的JSONobjects的值。 我使用JSON简单,它没有帮助很多! 我只能通过类似jsonstring = JSONArrayName.get(indx);的方法来获取包含JSONObjects的JSONArray元素。 但后来我无法从存储在“ jsonstring”字符串中的JSON对象读取值,请帮忙! 请在下面找到我的代码。
//这是我的客户端代码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
我将库更改为杰克逊,并且运行良好。 我必须对String进行一些调整,我必须删除字符串开头的引号,而在“ {}”末尾的引号,然后必须将所有存在的{}反斜杠替换为空格以获取有效的字符串格式{“ 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.