In the following example we will convert JSON string to Java object using ObjectMapper
class from the Jackson library. This class provides a method readValue(String, Class<T>)
which will deserialize a JSON string into Java object. The first argument to the method is the JSON string and the second parameter is the result type of the conversion.
In the code below you will see:
- Define a JSON string, here we have the
id
andname
keys. - Create a Jackson
ObjectMapper
which maps JSON string to POJO. - Map the
json
string into anArtist
object by calling thereadValue()
method. - Read the value of
artist
object properties.
package org.kodejava.jackson;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.kodejava.jackson.support.Artist;
import java.io.IOException;
public class JsonToObject {
public static void main(String[] args) {
String json = """
{
"id": 1,
"name": "The Beatles"
}
""";
ObjectMapper mapper = new ObjectMapper();
try {
Artist artist = mapper.readValue(json, Artist.class);
System.out.println("Artist = " + artist);
System.out.println("artist.getId() = " + artist.getId());
System.out.println("artist.getName() = " + artist.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is the definition of Artist
class.
package org.kodejava.jackson.support;
public class Artist {
private Long id;
private String name;
public Artist() {
}
public Artist(Long id, String name) {
this.id = id;
this.name = name;
}
// Getters & Setters
@Override
public String toString() {
return "Artist{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
The code snippet above will print to following output:
Artist = Artist{id=1, name='The Beatles'}
artist.getId() = 1
artist.getName() = The Beatles
Maven Dependencies
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Nice article. Found another article which does this using JS. https://codeblogmoney.com/convert-string-to-json-using-javascript/
Thanks Wayan, this helps 🙂
Please upload the
Artist
class file as well.Hi Sinha, I’ve added the
Artist
class definition.Thanks.