基本上,即时从包含名为“引用”的字符串数组的服务器的服务器获取JSON响应。如果没有找到之前的参考或者以前的参考填充,它可以是空的。如何从Java中的JSON字符串填充字符串数组
这是我从服务器得到的响应。
{"code":100,
"name":"3PVxkvfKyUiBg3LN24ek23KceGg6350KSkLZ.html",
"file":{
"author":"[email protected]",
"idx":"xihav-zupak-zonyf-bedid-cyvun-fahac-mykud",
"name":"html_file",
"references":[
"relec-toluz",
"rosah-vyzyh",
"rikik-cinom"
]
}
}
我在这个时刻做的不是很好,我第一次解析引用的内容,以确定然后创建新的String数组的引用数,并把每个值在里面。不过,我想知道是否有任何适当的方式来做到这一点。
这是我写的代码,这是不是一个真正的好的一段代码:
if(file.has("references")){
String s = file.get("references").toString();
int counter =0;
//determine the amount of elements (check if the references does not finish with ','
if(s.length() > 2 && s.charAt(s.length()-2) != ','){
counter++;
System.out.println(s);
for(int i=0 ; i < s.length(); i++){ if(s.charAt(i) == ',') counter++;}
}else {
counter++;
for(int i = 0; i < s.length() -2; i++){ if(s.charAt(i) == ',') counter++;}
}
JsonArray referencesList = new Gson().fromJson(s, JsonArray.class);
if(s != null && s.length()>2 && counter !=0){
System.out.println("1");
references = new String[counter];
for(int i = 0 ; i < references.length ; i++){ references[i] = referencesList.get(i).getAsString();}
}else references = new String[]{"No previous references found"};
}
的代码工作得很好了我的需要,但没有任何其他办法可以做到更“正确”?
你没有使用'JSONParser'任何理由吗?检查出:https://stackoverflow.com/questions/43724937/how-to-parse-json-string-to-java-object-with-jackson – yogidilip
@yogidilip以及我一直在使用Google的GSON为我的整个项目,因为我发现它更易于使用。这就是为什么。 – retArdos
那么你绝对应该考虑使用Gson的'JsonParser'。将解析留给Gson,只处理生成的'JsonElement'。 – Ishnark