Monday, 29 March 2021

Javax.json: Convert json string to JsonObject

Step 1: Get the instance of JsonReader from json string.

JsonReader jsonReader = Json.createReader(new StringReader(jsonStr));

 

Step 2: Get JsonObject by calling ‘readObject’ method on JsonReader instance.

JsonObject jsonObject = jsonReader.readObject();

 

Find the below working application.

 

StringToJsonObjectDemo.java

package com.sample.app;

import java.io.StringReader;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

public class StringToJsonObjectDemo {
	public static void main(String[] args) {
		String jsonStr = "{\"firstName\":\"Ram\",\"lastName\":\"Gurram\",\"id\":32,\"male\":false,\"dateOfBirth\":\"10/01/1985\"}\n";

		JsonReader jsonReader = Json.createReader(new StringReader(jsonStr));

		JsonObject jsonObject = jsonReader.readObject();
		System.out.println(jsonObject);
	}
}

Output

{"firstName":"Ram","lastName":"Gurram","id":32,"male":false,"dateOfBirth":"10/01/1985"}



 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment