convert string to json java code example
Example 1: convert json string to json object in java
try {
JSONObject jsonObject = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
}catch (JSONException err){
Log.d("Error", err.toString());
}
Example 2: decode json file in java tutorial
package com.howtodoinjava.demo.jsonsimple;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class WriteJSONExample
{
@SuppressWarnings("unchecked")
public static void main( String[] args )
{
JSONObject employeeDetails = new JSONObject();
employeeDetails.put("firstName", "Lokesh");
employeeDetails.put("lastName", "Gupta");
employeeDetails.put("website", "howtodoinjava.com");
JSONObject employeeObject = new JSONObject();
employeeObject.put("employee", employeeDetails);
JSONObject employeeDetails2 = new JSONObject();
employeeDetails2.put("firstName", "Brian");
employeeDetails2.put("lastName", "Schultz");
employeeDetails2.put("website", "example.com");
JSONObject employeeObject2 = new JSONObject();
employeeObject2.put("employee", employeeDetails2);
JSONArray employeeList = new JSONArray();
employeeList.add(employeeObject);
employeeList.add(employeeObject2);
try (FileWriter file = new FileWriter("employees.json")) {
file.write(employeeList.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example 3: how to convert json to java object
Jackson Data-bind depdendency that take care of
Converting between
JSON to Java Object
and
Java Object to JSON
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.0</version>
</dependency>