Java String to JSON Object

Java String to JSON Object

How to parse a string (which contains a JSON structure) into a JSON object? Here are a few ways to do it. Please refer to the following article for specific details.

To convert a string to a JSON object, you can use different Java libraries. Below are examples using three different libraries: Gson library, JSON-Simple library, and Jackson library. These libraries all provide functionality to convert a string into a JSON object.

Gson library

First, let's take a look at an example using the Gson library:

import com.google.gson.Gson;

public class JsonStringToJsonObjectExample {
    public static void main(String args[]) {
        String jsonString = "{\"domain\":\"json2.top\",\"author\":\"xingstarx\"}";
        Gson gson = new Gson();
        WebSite website = gson.fromJson(jsonString, WebSite.class);
        System.out.println(website.getDomain());
        System.out.println(website.getAuthor());
    }
}

JSON-Simple library

Next is an example using the JSON-Simple library:

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonStringToJsonObjectExample {
    public static void main(String args[]) {
        String jsonString = "{\"domain\":\"json2.top\",\"author\":\"xingstarx\"}";
        JSONParser parser = new JSONParser();
        try {
            JSONObject json = (JSONObject) parser.parse(jsonString);
            System.out.println(json.get("domain"));
            System.out.println(json.get("author"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

Jackson library

Finally, here is an example using the Jackson library:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonStringToJsonObjectExample {
    public static void main(String args[]) {
        String jsonString = "{\"domain\":\"json2.top\",\"author\":\"xingstarx\"}";
        ObjectMapper mapper = new ObjectMapper();
        try {
            WebSite website = mapper.readValue(jsonString, WebSite.class);
            System.out.println(website.getDomain());
            System.out.println(website.getAuthor());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

These examples demonstrate how to convert strings to JSON objects using different Java libraries. You can choose a suitable library according to your own needs to convert strings to JSON objects.

Relative Articles

Why JSON preferred over XML?    Optimizing Efficiency: Best Practices for JSON Compression     Mastering JSON Compression: Techniques, Tools, and Performance Optimization     Java Object to JSON String