basically im getting a JSON response from the server containing a key called "references" which is a String array. It can be either empty when no previous reference is found or filled with previous references.
Here is the response i get from the server.
{"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"
]
}
}
What I am doing at this moment is not very good, I first parse the content of references to determine the number of references then I create of new String array and put each value in it. However I am wondering if there is any proper way to do it.
Here's the code I wrote, which is not really a nice piece of code:
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"};
}
The code is working just fine for my need but is there any other way to do it more "properly" ?
JSONParser? Check out: stackoverflow.com/questions/43724937/…JsonParser. Leave the parsing to Gson and deal only with the resultingJsonElement.