Parsing a Json array using Play Framework and Java

I have the following Json structure:

{ "name": "John", "surname": "Doe", "languages": [ {"language": "english", "level": "3"}, {"language": "french", "level": "1"} ] } 

I am using the Play Framework to parse Json data from an HTTP message that was sent using a self-developed REST service. I already know how I can parse the first and last name from the Json data by looking at the documentation, this is done with:

 JsonNode json = request().body().asJson(); String name = json.findPath("name").textValue(); String surname = json.findPath("surname").textValue(); 

Now my question is how can I parse the "languages" of the array in Json data. I found several other posts about this issue, but they all used Scala, which I can’t tear myself away from, so I prefer the Java solution.

I have already tried several things, for example, for example:

  List<JsonNode> languages = json.findPath("languages").getElements(); 

According to the documentation, json.findPath () returns a JsonNode to which you can call the getElements () function, which will return an Iterator JsonNode. But I get a compilation error in getElements: "The getElements () method is undefined for the JsonNode type"

Does anyone know a simple way to parse such an array? thanks in advance

+6
source share
2 answers

You can do this in every loop like this:

 JsonNode json = request().body().asJson(); for (JsonNode language : json.withArray("languages")) { Logger.info("language -> " + language.get("someField").asText()); //do something else } 

Or if you are in lambdas:

 json.withArray("languages").forEach(language -> Logger.info("language -> " + language)); 

Also ... the correct way to create an ArrayNode :

 //using a mapper(important subject the mapper is) ObjectMapper mapper = new ObjectMapper(); ArrayNode array = mapper.createArrayNode(); //using an existing ArrayNode from a JsonNode ArrayNode array = json.withArray("fieldName"); //or using Play Json helper class ArrayNode array = Json.newArray(); 

You should really learn more about the features of jackson / quickxml. This is a very effective library. A good start is JacksonInFiveMinutes .

+11
source

Try the following:

 JsonNode node = (JsonNode)json.findPath("languages"); ArrayNode arr = (ArrayNode)node; Iterator<JsonNode> it = arr.iterator(); while (it.hasNext()) { JSONObject obj = it.next(); System.out.println("language: " + obj.findPath("language").getTextValue(); } 

Here I just print one of the elements, but you can do whatever you want, of course :)

Hope this helps.

+1
source

Source: https://habr.com/ru/post/986498/


All Articles