Java json string to object gson

Blog

How to convert json string to json object in java / Various ways to convert string to json object in java

  • Post author: codippa
  • Post published: April 10, 2019
  • Post category: J2SE (Core Java)
  • Post comments: 0 Comments

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home3/codippac/public_html/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

What is JSON?
JSON stands for JavaScript Object Notation and has become the most popular format for transfer and storage of data since due to its light weight nature.

Data between client and server can only be transferred in the form of a string. A json object can be easily converted to a string and vice-versa. Also, it is pretty easy to traverse across a json object for retrieving values.
A json string or json object stores data in key-value format and it can also represent complex parent-child relationships thus making it a preferred way to store and transmit data.
Why String to json object java?
Since json is now frequently used to store data, there might be a case that in your java application, you have a string which is in json format stored in a database or a file or through a form submit event.
The application needs to find value of some key or iterate over this string or display it in a tree view etc. All these are only possible when you have an object representation of this json string.
Fortunately, there are many libraries which make it possible to convert a json string to object in java. Note that all the libraries parse the json string. Thus, the json string should represent a valid json else an error will be thrown.
This post will discuss different libraries that can be utilized for this purpose.
Method 1 : Using org.json library
org.json library is also called JSON-Java library. It has org.json.JSONObject class which is used to convert a json string to a json object and vice-versa, create a json object programatically etc.
This class has a constructor which takes a string as argument and returns an instance of org.json.JSONObject which is an object representation of the supplied json string.
This object can also be used to retrieve value for a key from generated json object. Example,

import org.json.JSONObject; class StringToJsonObject { public static void main(String[] args) { // json string String jsonStr = "\"name\": \"i30\", \"brand\": \"Hyundai\">"; // convert to json object JSONObject json = new JSONObject(jsonStr); // print object System.out.println(json.toString()); // get value for a key String brand = json.get("brand"); // print value System.out.println(brand); } }

import org.json.JSONObject; class StringToJsonObject < public static void main(String[] args) < // json string String jsonStr = ""; // convert to json object JSONObject json = new JSONObject(jsonStr); // print object System.out.println(json.toString()); // get value for a key String brand = json.get("brand"); // print value System.out.println(brand); > >

Читайте также:  Joomla html code module

Above code when executed produces the following output

Источник

Java Gson – Convert JSON string to a java object

Google json provides methods to convert a JSON string to a Java object. Gson uses the name to match the json property to the java field. There are two ways to convert json to java.

    Using the com.google.gson.Gson class. Create a new instance of this class and use the method

public T fromJson(String json, Class classOfT)

Let’s look at an example. For this example we consider java objects of non generic type only

Part A : Converting JSON to a java object

In this example we use the Gson library to de-serialize json from free music archive. We need a java class that mimics the structure of the json image. In the second half of the tutorial we will see how to build that java class, but for now, let’s assume that we have a Java class that corresponds to the JSON structure. The main class is the Albums class and it contains the list of Datasets. Each Dataset is one album.

class Dataset < public String album_id; public String album_title; @SerializedName("album_images") Listimages = new ArrayList(); >

Here’s the main method that shows how GSON can convert the album JSON string to a java object.

// url is the free music archive url. Albums albums = gson.fromJson(IOUtils.toString(new URL(url)), Albums.class);

Part B : Building the Java class corresponding to the JSON string

In Part A, we converted the JSON string to a java object. However, how do we build the java object in the first place? Lets see this in action. If you look at the JSON, it starts with a root object that has properties such as title, message, errors, etc.

Lets ignore the dataset for now. Lets just build a java class to hold the root. We call that class Albums. We will make the fields public for brevity, but you might want to make them private and use setters.

class Albums < public String title; public String message; public String[] errors = new String[]<>; public String total; public int total_pages; public int page; public String limit; >

Lets convert this to JSON and see how it looks

import com.google.gson.Gson; public class JavaToJsonAndBack < public static void main(String[] args) < Albums albums = new Albums(); albums.title = "Free Music Archive - Albums"; albums.message = ""; albums.total = "11259"; albums.total_pages = 2252; albums.page = 1; albums.limit = "5"; GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); System.out.println(gson.toJson(albums)); >>

This is how the resulting JSON looks like

This is a good beginning. Notice how we initialized errors to an empty array. Otherwise Gson would think its null and either ignore it or print null if we allow null serialization. In this case, it looks like we are better off with using a List for errors. Lets change the errors variable to

public List errors = new ArrayList();

We have used a GsonBuilder since that allows us to customize the conversion. we will see its benefit later in the example. The next step is to build a class for the dataset. Lets see how the dataset JSON looks

Читайте также:  Google works on python

For this tutorial we will be considering only some fields from ‘dataset’ and ‘album_images’. The other fields can be added similarly. The dataset contains an array of album and each album contains, besides other fields, an array of album_images. We build a java class for each JSON object. We have already built a java class for albums. Now lets built classes for dataset and album_image.

class Dataset < public String album_id; public String album_title; >class AlbumImages

Dataset dataset = new Dataset(); dataset.album_id = "7596"; dataset.album_title = "Album 1"; System.out.println(gson.toJson(dataset));
AlbumImages image = new AlbumImages(); image.image_id = "1"; System.out.println(gson.toJson(image));

See how gson has not printed user_id since its null. We need to be able to tell json to serialize null fields too. GsonBuilder helps us do that

The album image json now looks like this

Lets now wire up the dataset into the albums class and the AlbumImage into the dataset class. To the Albums class we add the List of Dataset

List dataset = new ArrayList();

To the Dataset class we add a List of images

List images = new ArrayList();

Lets change the main method to add dataset to the album and image to the dataset

dataset.images.add(image); albums.dataset.add(dataset);

Here’s how our JSON looks now

Lets turn on pretty printing so that our JSON looks better. However, we do that only during developement. If you are actually designing a server that provides JSON data, then make the JSON as compact as possible.

builder.setPrettyPrinting().serializeNulls();

Here’s our formatted JSON now

This looks good, however we want to change the name of the ‘images’ element in dataset to ‘album_images’. Lets assume we cant change the java name because it follows the java naming policy. We can use annotation on the field to specify the json name to use for a particular java property. Here’s how to do that

@SerializedName("album_images") List images = new ArrayList();

our JSON now contains the name ‘album_images’

If you dont want to bind your java class to GSON then there is another way to do this. Lets add one more field to the AlbumImage class. We call it albumId. However, we want to name the field album_id in the JSON. To do that we need to specify a NamingStrategy in the GsonBuilder.

builder.setFieldNamingStrategy(new FieldNamingStrategy() < @Override public String translateName(Field f) < if (f.getName().equals("albumId")) return "album_id"; else return f.getName(); >>);

The translateName method is called for all fields and if the name matches albumId we convert the name to album_id and send it back otherwise we send the default. the album_images element now looks like this

GsonBuilder provides a lot of other customization. You can disable HTML escaping, exclude fields with specific modifiers (e.g. exclude all protected fields), set custom type adapters, set exclusion policies etc. Look at the GsonBuilder JavaDoc for the complete list. You can now use the Albums class and parse the JSON using the fromJson method (you will have to add the other properties) as shown in part A.

Part C : Java to JSON

While we are here, Let’s now use GSON library to create json from the Java object that we just built.

public static void main(String[] args) < Albums albums = new Albums(); albums.title = "Free Music Archive - Albums"; albums.message = ""; albums.total = "11259"; albums.total_pages = 2252; albums.page = 1; albums.limit = "5"; GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting().serializeNulls(); builder.setFieldNamingStrategy(new FieldNamingStrategy() < @Override public String translateName(Field f) < if (f.getName().equals("albumId")) return "album_id"; else return f.getName(); >>); Gson gson = builder.create(); Dataset dataset = new Dataset(); dataset.album_id = "7596"; dataset.album_title = "Album 1"; AlbumImages image = new AlbumImages(); image.image_id = "1"; image.albumId = "10"; dataset.images.add(image); albums.dataset.add(dataset); System.out.println(gson.toJson(albums)); >

Источник

Читайте также:  Python http server log

Parse JSON Strings in Java Objects with Gson API

This tutorial covers How to Parse JSON in Java. You will learn to use Gson API to convert JSON Strings into Java Objects with the help of examples.

Setup

Let’s begin with setting up the essentials. To use Gson API, we will have to add it as a dependency. Also, we will create a Java Pojo class that will be our target.

Gson Dependency

Use the latest version of Gson API.

dependency> groupId>com.google.code.gson groupId> artifactId>gson artifactId> version> version> dependency>Code language: HTML, XML (xml)

Or, in build.gradle

compile group: 'com.google.code.gson', name: 'gson', version: '' Code language: Gradle (gradle)

Java POJO Class

We will create the Account.java class.

package com.amitph.spring.tutorials.students.model; public class Account < private long accountNumber; private String accountHolder; private String type; private double balance; public long getAccountNumber() < return accountNumber; > public void setAccountNumber(long accountNumber) < this.accountNumber = accountNumber; > public String getAccountHolder() < return accountHolder; > public void setAccountHolder(String accountHolder) < this.accountHolder = accountHolder; > public String getType() < return type; > public void setType(String type) < this.type = type; > public double getBalance() < return balance; > public void setBalance(double balance) < this.balance = balance; > >Code language: Java (java)

JSON to Object using Gson

Let’s try an example of using Gson to Parse JSON String into an Object.

String json = """ < "accountNumber":1234, "accountHolder":"Strong Belwas", "type":"Savings", "balance":1239.39 > """; Gson gson = new Gson(); Account account = gson.fromJson(json, Account.class); System.out.println(account);Code language: Java (java)

Here, we are using Java Text Blocks to hold multiline JSON String.

JSON to Map using Gson

To convert JSON into a Map, which has a generic type, we need to create a Type instance.

The following example demonstrates using Gson to parse JSON string to a Map.

String json = """ < "accountNumber":1234, "accountHolder":"Strong Belwas", "type":"Savings", "balance":1239.39 > """; Gson gson = new Gson(); Type type = new TypeToken>() <>.getType(); Map account = gson.fromJson(json, type);Code language: Java (java)

JSON to Map of Objects using Gson

Similarly, we can cast a JSON to Map of custom objects by using the correct Type .

String json = """ < "1234":< "accountNumber":1234, "accountHolder":"Strong Belwas", "type":"Savings", "balance":1239.39 > > """; Gson gson = new Gson(); Type type = new TypeToken>() <>.getType(); Map account = gson.fromJson(json, type);Code language: Java (java)

JSON to Array of Objects using Gson

The JSON String is an array of Students we can map it to Student[] .

String json = """ [< "accountNumber":1234, "accountHolder":"Strong Belwas", "type":"Savings", "balance":1239.39 >] """; Gson gson = new Gson(); Student[] students = gson.fromJson(json, Student[].class);Code language: Java (java)

Summary

In this short tutorial, we have learned How to use Gson API. We have covered examples to parse JSON Strings into Java Objects, Maps, and Arrays.
For more on Java, please visit Java Tutorials.

Источник

Оцените статью