Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a JSON string to an array using Jackson

Tags:

java

json

jackson

I have a String with the following value:

[   {     "key1": "value11",     "key2": "value12"   },   {     "key1": "value21",     "key2": "value22"   } ] 

And the following class:

public class SomeClass {     private String key1;     private String key2;     /* ... getters and setters omitted ...*/ } 

And I want to parse it to a List<SomeClass> or a SomeClass[]

Which is the simplest way to do it using Jackson ObjectMapper?

like image 313
mmutilva Avatar asked Aug 30 '11 16:08

mmutilva


People also ask

Can we convert JSON string to array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.

How does Jackson parse JSON?

databind. ObjectMapper ) is the simplest way to parse JSON with Jackson. The Jackson ObjectMapper can parse JSON from a string, stream or file, and create a Java object or object graph representing the parsed JSON. Parsing JSON into Java objects is also referred to as to deserialize Java objects from JSON.

How do you convert JSON to an array?

Convert JSON to Array Using `json.The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.

Can JSON parse parse an array?

parse method to parse a JSON array into its JavaScript equivalent. The only parameter we passed to the method is the JSON string that should be parsed. If you provide invalid JSON to the method, a SyntaxError exception is thrown.


1 Answers

I finally got it:

ObjectMapper objectMapper = new ObjectMapper(); TypeFactory typeFactory = objectMapper.getTypeFactory(); List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class)); 
like image 189
mmutilva Avatar answered Oct 07 '22 06:10

mmutilva