【发布时间】:2017-06-22 14:48:21
【问题描述】:
基本上我从服务器获得一个 JSON 响应,其中包含一个名为“references”的键,它是一个字符串数组。当没有找到以前的引用时,它可以是空的,也可以用以前的引用填充。
这是我从服务器得到的响应。
{"code":100,
"name":"3PVxkvfKyUiBg3LN24ek23KceGg6350KSkLZ.html",
"file":{
"author":"test@test",
"idx":"xihav-zupak-zonyf-bedid-cyvun-fahac-mykud",
"name":"html_file",
"references":[
"relec-toluz",
"rosah-vyzyh",
"rikik-cinom"
]
}
}
我现在做的不是很好,我首先解析引用的内容以确定引用的数量,然后创建新的字符串数组并将每个值放入其中。但是我想知道是否有任何适当的方法可以做到这一点。
这是我写的代码,这不是一段很好的代码:
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?签出:stackoverflow.com/questions/43724937/… -
@yogidilip 我在整个项目中一直使用 Google 的 GSON,因为我发现它更易于使用。这就是为什么。
-
那你一定要考虑使用Gson的
JsonParser。将解析留给 Gson,只处理生成的JsonElement。 -
同意大多数 cmets,不要使用“手动代码”,而是准备好并经过测试的解析器