🌐
Tabnine
tabnine.com › home page › code › java › leap.lang.json.jsonobject
leap.lang.json.JsonObject.getList java code examples | Tabnine
public MApiModelBuilder readModel(String name, Map<String,Object> map, SwaggerExtension ex) { MApiModelBuilder mm = new MApiModelBuilder(); JsonObject model = JsonObject.of(map); List<String> requiredProperties = model.getList(REQUIRED); mm.setName(name); mm.setTitle(model.getString(TITLE)); mm.setSummary(model.getString(SUMMARY)); mm.setDescription(model.getString(DESCRIPTION)); mm.setEntity(model.getBoolean(X_ENTITY, false)); Map<String,Object> properties = model.getMap(PROPERTIES); if(null != properties) { List<MApiPropertyBuilder> list = readProperties(properties, requiredProperties, ex); list.forEach(mm::addProperty); } return mm; }
🌐
TutorialsPoint
tutorialspoint.com › how-to-get-the-values-of-the-different-types-from-a-json-object-in-java
How to get the values of the different types from a JSON object in Java?
Create a JSONObject object and pass the JSON string to it. Use the getString(), getInt(), getDouble(), and getBoolean() methods to extract the values of different types from the JSON object.
Top answer
1 of 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;
        }
2 of 2
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]
🌐
Baeldung
baeldung.com › home › json › get a value by key in a jsonarray
Get a Value by Key in a JSONArray | Baeldung
January 8, 2024 - On invoking getValuesForGivenKey(jsonArrayStr, “name”) where jsonArrayStr is our example JSON, we’ll get a List of all names as the output: ... In this quick article, we learned how to parse a JSONArray to get all the mapped values for ...
🌐
Stack Overflow
stackoverflow.com › questions › 52204223 › how-to-get-the-list-of-objects-from-json-using-java-and-gson
How to get the list of objects from Json using Java and Gson - Stack Overflow
I try to read from a Json file and convet it to Java object, I have the following Java code to read the Json: class Item { String name; int itemId; Date AddTime; String group; } G...
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 17308977 › how-to-get-list-from-json-data-in-java
how to get list from json data in java - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... public static void main(String[] args) throws IOException { String json = getJSON().substring(getJSON().indexOf("[")+1,getJSON().indexOf("]")); Users user = new Gson().fromJson(json, Users.class); WriteLine("["+user.getID()+"]"+" "+user.getFirstName()+" "+user.getLastName()+" "+user.getCompany()+" "+user.getEMail()+" "+user.getPhoneNo()); } static void WriteLine(String text){ System.out.print(text); } static String getJSON() throws IOException { URL url = new URL("http://localhost:51679/api/User
🌐
Coderanch
coderanch.com › t › 777123 › java › retrieving-values-json-string
retrieving values from json string. (Java in General forum at Coderanch)
October 16, 2023 - When I'm trying to do the following: I'm getting this message "Unlikely argument type for equals(): JsonNode seems to be unrelated to String ". Wondering how can I do comparision here? ... Jack Tauson wrote:What is "EventDataRequestJson" here? Thanks! That would be a custom class you make to mimic the structure of the JSON. (In some cases, it may be an already-existing class in a library you're using.). I agree with Stephan that this is the preferred way to use an ObjectMapper, especially if you're going to need to use all (or most) of the data in the document - but if you're new to parsing JSON like this, you may need to work your way up to that.
🌐
Medium
medium.com › @Mohd_Aamir_17 › mastering-json-in-java-a-comprehensive-guide-to-handling-json-objects-arrays-and-nodes-with-df57bf0ebff1
Mastering JSON in Java: A Comprehensive Guide to Handling JSON Objects, Arrays, and Nodes with Jackson | by Mohd Aamir | Medium
November 4, 2024 - This article offers an in-depth look at how to parse, create, and manipulate JSON objects, arrays, and nodes using the Jackson library, covering advanced scenarios to equip you with the tools to tackle complex JSON data in Java.
🌐
Coderanch
coderanch.com › t › 744956 › java › key-JSONArray
Get key:value from JSONArray (Java in General forum at Coderanch)
Take values from JSON file, and store that values into ArrayList, then sort it. The problem is that my json is array, and i do not know how to get just one pair, what is wrong with my code, can you help me?Please.
Top answer
1 of 3
2

There are several ways to retrieve the json array value:

Assume we have a jsonString

jsonString = "{\n" + "     \"firstNames\": [ \n" + "          \"Aaron\",\n" + "          \"Abigail\",\n" + "          \"Albert\",\n" + "          \"Bob\"\n" + "     ]\n" + "}";

(since many classes share similar names, I am using the groupId and artifactId for distinction.)

Simple cases: use generic JSONObjects and JSONArrays.

json-simple (which OP is using) json-simple website, maven :

org.json.simple.parser.JSONParser jsonParser = new org.json.simple.parser.JSONParser();
org.json.simple.JSONObject firstObject = (org.json.simple.JSONObject) jsonParser.parse(jsonString);
org.json.simple.JSONArray jsonArray = (org.json.simple.JSONArray) firstObject.get("firstNames");
System.out.println(jsonArray);

JSON in Java (mentioned in adendrata's answer): JSON-Java doc, maven

org.json.JSONObject secondObject = new org.json.JSONObject(jsonString);
org.json.JSONArray jsonArray2 = secondObject.getJSONArray("firstNames");
System.out.println(jsonArray2);

gson: Gson, maven

com.google.gson.JsonObject thirdObject = com.google.gson.JsonParser.parseString(jsonString).getAsJsonObject();
System.out.println(thirdObject.get("firstNames").getAsJsonArray());

For more complicated use cases, if you'd like to define your own class, and want to deserialize JSON string to your class, then you can use Gson or Jackson:


// Create your own class:
/*
public class YourOwnClass {
    private List<String> firstNames;

    public List<String> getFirstNames() {
        return firstNames;
    }
}
*/

Gson gson = new Gson();
YourOwnClass customObject1 = gson.fromJson(jsonString, YourOwnClass.class);
System.out.println(customObject1.getFirstNames());

ObjectMapper mapper = new ObjectMapper();
YourOwnClass customObject2 = mapper.readValue(jsonString, YourOwnClass.class);
System.out.println(customObject2.getFirstNames());

2 of 3
0

you can use JSONArray to get array type of Json and looping to access each index

example:

    JSONArray array = firstObject.getJSONArray("firstNames");
    for (int i = 0; i < array.length(); i++) {
        System.out.println("Hello i'm " + array.get(i));
    }