2

I have below json string and would like to access the alsoKnownAs list using Java. I am able to getString for the name, I have tried getJSONArray for alsoKnownAs but it doesn't quite workout

{\"name\":\"moses\",\"alsoKnownAs\":[\"njai\", \"njenga\",\"musa\"]}

I can access the name as below but I can't the equivalent of getString method that would return a list of strings or equivalent of getJSONArray for a list of strings

    public static Person parsePersonJson(String json) {

            JSONObject currentPerson;
            String name;

            try {
                currentPerson = new JSONObject(json);

                // so I can access the name like

                name = currentPerson.getString("name");

               //I was trying this to get the list but figure out I was using a list of json objects, so not how to get the list of stings

           JSONArray arrayKnownAs = names.getJSONArray("alsoKnownAs");
                List<String> alsoKnownAs= new ArrayList<>();

                for (int i = 0, l = arrayKnownAs.length(); i < l; i++) {
                    String origin;
                    origin = arrayKnownAs[i];
                    alsoKnownAs.add(origin);
                }



               Person thisPerson =  new Person(

                //I instantiate person object here

                );
                return thisPerson;

            } catch (org.json.JSONException e) {
    // error
            }
            return null;
        }
6
  • 3
    You could write your own JSON parser. Or you could just use one of the many already existing and battle-tested ones. If you have tried doing so, and had a problem, then post the code you tried, and tell us precisely what the error is. Otherwise, your question boils down to "how to parse JSON in Java", and is a duplicate. Commented Aug 5, 2018 at 9:16
  • @JBNizet I have added some clarification and how am approaching it Commented Aug 5, 2018 at 9:41
  • What do you expect to happen and what happens instead? Commented Aug 5, 2018 at 9:46
  • stackoverflow.com/questions/45519786/get-json-array-from-php/….. this might help Commented Aug 5, 2018 at 9:50
  • Thanks @user3678528 for the suggestion, I am okay accessing a list of JSONOjects which I can get by getJSONArray I am trying to get the list of strings in which case if I use getJSONArray I get incompatible types Commented Aug 5, 2018 at 9:55

2 Answers 2

3

If anyone else is stuck here, It turned out I was on the right track, I can access the List using getJSONArray, but when iterating for each member, I use getString

 public static Person parsePersonJson(String json) {

            JSONObject currentPerson;
            String name;

            try {
                currentPerson = new JSONObject(json);

                // so I can access the name like

                name = currentPerson.getString("name");

                List<String> alsoKnownAs= new ArrayList<>();

                //use getJSONArray to get the list

                JSONArray arrayKnownAs = currentPerson.getJSONArray("alsoKnownAs");

                for (int i = 0, l = arrayKnownAs.length(); i < l; i++) {

                 //This is where I was getting it wrong, i needed to use getString to access list items

                  alsoKnownAs.add(arrayKnownAs.getString(i));
                   }



               Person thisPerson =  new Person(

                //I instantiate person object here

                );
                return thisPerson;

            } catch (org.json.JSONException e) {
             // error
            }
            return null;
        }
Sign up to request clarification or add additional context in comments.

Comments

2

Here a solution using com.fasterxml.jackson

Person.java:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

class Person  {
    final public String name;
    final public List<String> alsoKnownAs;

    @JsonCreator
    public Person(
            @JsonProperty("name") final String name,
            @JsonProperty("alsoKnownAs") final List<String> alsoKnownAs
    ) {
        this.name = name;
        this.alsoKnownAs = alsoKnownAs;
    }

    public static Person parsePersonJson(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, Person.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Here a quick test:

PersonTest.java

import org.junit.Test;

public class PersonTest {


    @Test
    public void parseAJsonToAPerson() {
        String json = "{\"name\":\"moses\",\"alsoKnownAs\":[\"njai\", \"njenga\",\"musa\"]}";
        Person currentPerson = Person.parsePersonJson(json);

        System.out.println("name: " + currentPerson.name);
        System.out.println("alsoKnownAs: " + currentPerson.alsoKnownAs);

    }

}

Test output is:

name: moses
alsoKnownAs: [njai, njenga, musa]

1 Comment

Thanks a lot @Simonluca for that.

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.