2

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" ?

4
  • 2
    Any reason you are not using a JSONParser? Check out: stackoverflow.com/questions/43724937/… Commented Jun 22, 2017 at 14:58
  • @yogidilip well i've been using Google's GSON for my whole project because i found it easier to use. That's why. Commented Jun 22, 2017 at 15:04
  • 2
    Then you should definitely consider using Gson's JsonParser. Leave the parsing to Gson and deal only with the resulting JsonElement. Commented Jun 22, 2017 at 15:07
  • Agree with most comments, do not use 'manual code' but ready and tested parser Commented Jun 23, 2017 at 9:38

3 Answers 3

0
if you wan to do this properly, you need before to create a pojo class for your json

public class ClassName{

private String code;
private String name;
private MyFile file;
......
}

public class MyFile{

private String author;
private String idx;
......
}

Now after that, you're ready to map your json on your pojo object, you can do it easly using jackson.


for your documentation

https://github.com/FasterXML/jackson-docs

So you need to add jackson on your project and you can do something like this for your mapping.

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'qdqsdqs'}";


//JSON from URL to Object
ClassName result = mapper.readValue(jsonInString , ClassName.class);
Sign up to request clarification or add additional context in comments.

Comments

0

A good start would be to parse the Json using a Json Parser. Since you're using Gson, you should look into JsonParser to do your parsing. Better not to do it manually.

Some key steps include:

  1. Parse the Json (I'll take the json you gave me and use it as a String, but you can just as easily parse it from a file) and get a JsonElement
  2. Look at the file member of the JsonElement, which is in turn a JsonElement and look at that JsonElement's references member, which you know is a JsonArray.
  3. Iterate through the JsonArray and add to a list of Strings. Return that list of Strings as a String[]

    public static void main(String[] args) {
        String json = "{\"code\":100,\n" +
                "\n" +
                " \"name\":\"3PVxkvfKyUiBg3LN24ek23KceGg6350KSkLZ.html\",\n" +    
                "\n" +
                "  \"file\":{\n" +
                "         \"author\":\"test@test\",\n" +
                "\n" +
                "         \"idx\":\"xihav-zupak-zonyf-bedid-cyvun-fahac-mykud\",\n" +
                "\n" +
                "         \"name\":\"html_file\",\n" +
                "\n" +
                "         \"references\":[\n" +
                "                \"relec-toluz\",\n" +
                "\n" +
                "                \"rosah-vyzyh\",\n" +
                "\n" +
                "                \"rikik-cinom\"\n" +
                "        ]\n" +
                "   }\n" +
                "}";
        JsonElement element = new JsonParser().parse(json);
        System.out.println(Arrays.toString(getReferences(element)));
    
    }
    
    private static String[] getReferences(JsonElement jsonElement) {
        List<String> refList = new ArrayList<>();
        JsonArray references = jsonElement.getAsJsonObject().get("file").getAsJsonObject().get("references").getAsJsonArray();
        references.forEach((reference) -> refList.add(reference.getAsString()));
        return refList.toArray(new String[0]);
    }
    

Comments

0

I was parsing on my own and not doing this right. So I rewrote some part, removed the counter part and just discovered the size() method for JSonArray which I had not checked before.

My final piece of code is shorter and easier to read.

 String[] references = null;

 String repCode = "
 {
   "code":100,

   "name":"3PVxkvfKyUiBg3LN24ek23KceGg6350KSkLZ.html",

   "file":{
     "author":"test@test",

     "idx":"xihav-zupak-zonyf-bedid",

     "name":"random",

     "references":[
            "relec-toluz",

            "rosah-vyzyh",

            "rikik-cinom"
      ]
   }
}"

The String repCode is the response I get from the server that I query.

JsonObject file = new Gson().fromJson(repCode.get("file").toString(),JsonObject.class);

if(file.has("references") &&  file.get("references").isJsonArray()){
    JsonArray referencesList = file.get("references").getAsJsonArray();

    if(referencesList.size() != 0){
        references = new String[referencesList.size()];
        for(int i = 0 ; i < references.length ; i++){
             references[i] = referencesList.get(i).getAsString();
        }
    }else references = new String[]{"No previous references found"};
}

Finally to display:

 for(String ref: references){
        System.out.println("Ref: " + ref);
    }

Which give the following output:

Ref: relec-toluz
Ref: rosah-vyzyh
Ref: rikik-cinom

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.