我被困在这里两天,试图读取存储在JSONArray中的JSONobjects的值。我使用JSON简单,它没有帮助很多!我只能通过像jsonstring = JSONArrayName.get(indx)这样的东西来获取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
答案 0 :(得分:0)
我将图书馆更改为杰克逊,它的工作完美无缺。 我不得不对我的String tho进行一些调整,我不得不删除字符串开头的引号和末尾的引号“{}”然后我必须替换所有{}反斜杠存在的空格以获得有效的字符串格式{“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();