[英]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.