Parse json string with java

How to parse a JSON String into an object with Java

The JSON format is one of the most used data format for storing and exchanging information using computers.

Although you can parse a JSON string as a JSON object without these libraries, it’s generally not recommended unless you are prepared to put in the required effort.

Without using third-party libraries, you need to implement the JSON parser specification according to the ECMA International specification that you can find here.

You need to test the parser library you’ve created and then be prepared to maintain and improve that library. You also need to write code that can handle the wrong JSON string format well or you might produce the wrong output.

In short, it’s better to use a tried-and-tested JSON library for Java that has been developed by many developers and is mature enough to handle many use cases.

This tutorial will help you learn how to parse JSON strings into objects and vice versa using the three libraries mentioned above.

Let’s start with the Gson library.

Parse JSON in Java using the Gson library

The Gson library is a Java library used to convert Java objects into their JSON representation and vice versa.

One notable feature of the Gson library is the full support for Java generics.

Once you add the library as a dependency to your Java project, you can use the fromJson() method to convert a string into a Java object.

For example, suppose you have a Java class named Person with the following definitions:

You can parse a string as an instance of the Person class as follows:

You can convert the object back into a String with the toJson() method of the Gson library as shown below:

And that’s how easy it is to parse a JSON string into a Java object using Gson.

You can find more detailed information about the library on the Gson Github page

Parse JSON in Java using the Jackson library

The Jackson library is a data-processing tool for Java that can process not only JSON data format, but also others like CSV, TOML, YAML, or XML.

Still, Jackson became popular among Java and Android developers because of its ability to parse streaming JSON data.

To parse a JSON string into a Java object with Jackson, you need to create a class with setters and getters for its fields as shown below:

Without the setters and getters, Jackson will have no access to the Person class fields

The code below shows how to parse a string into a JSON object using Jackson:

 """   First, you need to create an instance of the ObjectMapper class from Jackson. The instance is named mapper in the above code.

Next, you need to call the readValue() method from the mapper instance, passing the String variable as the first argument and the Java blueprint class as the second argument.

To parse a Java object into a JSON string, you need to call the writeValueAsString() method from the mapper instance as follows:

And that’s how you can parse a JSON string as a Java object using the Jackson library.

For advanced use and other Jackson add-on libraries, you can visit the Jackson Github page.

Parse JSON in Java using the JSON-java library

The JSON-java library is a lightweight Java library that can be used to parse a JSON string into a Java object and vice versa.

The library is doesn’t require you to pass a Java class as the JSON object blueprint.

Instead of your defined class instance, the object will be of the JSONObject instance.

The code below shows how you can use the JSON-java library to create an object from a JSON string:

To convert the JSONObject back into a String , you can call the toString() method from the instance as follows:

The JSONObject implementation is similar to the Java HashMap class, so the order of the key-value pairs won’t be preserved.

This is why the string output of the toString() method above is not in the same order as the original jsonStr variable.

And that’s how you can parse a JSON string using the JSON-java library.

For more information, you can visit the JSON-java Github page.

Now you’ve learned how to parse JSON string using Java with the three most popular JSON libraries. Well done! 👍

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

How to Parse JSON in Java

Last updated: 08 November 2019 In this tutorial we will look at how to parse JSON in Java using different libraries. JSON stands for JavaScript Object Notation, and it is based on a subset of JavaScript. As a data-exchange format, it is widely used in web programming. Here we show how to parse JSON in Java using the org.json library. A JSON object is an unordered set of key/value pairs. A JSON array is an ordered collection of values. The values themselves could be objects or arrays. We will be parsing this JSON as an example to retrieve values for pageName , pagePic and post_id

Parse JSON Using org.json

To use org.json to parse JSON in Java, you need to add the library as a dependency. This can be fetched from Maven repository

import org.json.JSONArray; import org.json.JSONObject; public class ParseJSON < static String json = ". "; public static void main(String[] args) < JSONObject obj = new JSONObject(json); String pageName = obj.getJSONObject("pageInfo").getString("pageName"); System.out.println(pageName); JSONArray arr = obj.getJSONArray("posts"); for (int i = 0; i < arr.length(); i++) < String post_id = arr.getJSONObject(i).getString("post_id"); System.out.println(post_id); >> > 

Parse JSON Using Gson

In order to use Gson to parse JSON in Java, you need to add the library as a dependency. You can get the latest version from Maven repository

The below example shows how to Parse the above JSON with Gson.

import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class ParseJSON < static String json = ". "; public static void main(String[] args) < JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString(); System.out.println(pageName); JsonArray arr = jsonObject.getAsJsonArray("posts"); for (int i = 0; i < arr.size(); i++) < String post_id = arr.get(i).getAsJsonObject().get("post_id").getAsString(); System.out.println(post_id); >> > 

Like the previous example, the . needs to be replaced by the JSON string.

Parse JSON Using JsonPATH

The above two examples require a full deserialization of the JSON into a Java object before accessing the value in the property of interest. Another alternative, which does not go this route is to use JsonPATH which is like XPath for JSON and allows traversing of JSON objects.

Like before, you need to add JsonPATH as a dependency, which can be fetched from Maven repository

For example, to parse the above JSON we can use:

import com.jayway.jsonpath.JsonPath; public class ParseJSON < static String json = ". "; public static void main(String[] args) < String pageName = JsonPath.read(json, "$.pageInfo.pageName"); System.out.println(pageName); Integer posts = JsonPath.read(json, "$.posts.length()"); for(int i=0; i < posts; i++) < String post_id = JsonPath.read(json, "$.posts[" + i + "].post_id"); System.out.println(post_id); >> > 

Источник

3 ways to convert String to JSON object in Java? Examples

It’s very common nowadays to receive JSON String from a Java web service instead of XML, but unfortunately, JDK doesn’t yet support conversion between JSON String to JSON object. Keeping JSON as String always is not a good option because you cannot operate on it easily, you need to convert it into a JSON object before you do anything else e.g. retrieve any field or set different values. Fortunately, there are many open-source libraries which allows you to create JSON object from JSON formatted String like Gson from Google, Jackson, and json-simple. In this tutorial, you will learn how to use these 3 main libraries to do this conversion with step-by-step examples.

Even though you can use a simple or complex JSON String with lots of attributes and JSON arrays, I’ll use the following JSON String for example purpose:

jsonString = < "name" : "Ronaldo", "sport" : "soccer", "age" : 25, "id" : 121, "lastScores" : [ 2, 1, 3, 5, 0, 0, 1, 1 ] >

It’s simple, has 5 attributes, two of which are String and the other two are numeric. One attribute, lastScore is a JSON array.

1. String to JSON Object using Gson

The Gson is an open-source library to deal with JSON in Java programs. It comes from none other than Google, which is also behind Guava, a common purpose library for Java programmers. You can convert JSON String to Java object in just 2 lines by using Gson as shown below :

Gson g = new Gson(); Player p = g.fromJson(jsonString, Player.class)

You can also convert a Java object to JSON by using the toJson() method as shown below

The good thing about Gson is that it’s feature-rich and comes from Google, which is known for performance.

2. JSON String to Java object using JSON-Simple

The JSON-Simple is another open-source library that supports JSON parsing and formatting. The good thing about this library is its small size, which is perfect for memory constraint environments like J2ME and Android.

JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(stringToParse);

The good thing about json-simple is that it is also JDK 1.2 compatible, which means you can use it on a legacy project which is not yet in Java 5.

3 ways to convert String to JSON object in Java?

3. String to JSON — Jackson Example

Jackson is I guess the most popular JSON parsing library in the Java world. It’s fast, feature-rich, and supports streaming which is great for parsing large JSON output from web services. Following one-liner convert JSON string representing a soccer player into a Java class representing player:

Player ronaldo = new ObjectMapper().readValue(jsonString, Player.class);

One of the drawbacks of Jackson is that it requires JDK 1.5 so if you are stuck in an earlier Java version then it may not fit there. Also, Jackson doesn’t support J2ME, but one of the main advantages of using Jackson is that it supports streaming which can be used to parse huge JSON responses without loading it fully in memory.

Jackson is a very popular and efficient Java library to map Java objects to JSON and vice-versa. If you want to learn the basics of the Jackson library and how to use them, I suggest you take a look at the Jackson documentation.

That’s all about how to convert String to JSON objects in Java. You can use any of the json-simple, Gson, or Jackson for parsing JSON messages received from web services, each of them has its own advantage. Json-simple has a small memory footprint means it’s quite suitable for J2ME and Android clients, while Jackson is feature-rich so better supported for a large project. Gson is in between them and my favorite general-purpose JSON parser in Java programs.

  • 5 JSON libraries Java JEE Programmer should know (list)
  • How to parse JSON to/from Java Object using Jackson? (tutorial)
  • How to use Google Protocol Buffer (protobuf) in Java? (tutorial)
  • Top 10 RESTful Web Service Interview Questions (see here)
  • What is the purpose of different HTTP methods in REST? (see here)
  • How to convert JSON to HashMap in Java? (guide)
  • 10 Things Java developers should learn? (article)
  • How to ignore unknown properties while parsing JSON in Java? (tutorial)
  • How to parse JSON with date fields in Java? (example)
  • 5 Courses to learn RESTful API and Web services in Java? (courses)
  • 10 free courses to learn Java in-depth (resource)
  • How to convert JSON array to String array in Java using Gson? (tutorial)
  • How to parse a large JSON file using Jackson Streaming API? (example)

Thanks for reading this article so far. If you like these 3 ways to convert String to JSON object in Java, then please share with your friends and colleagues. If you have any questions or feedback, then please drop a note.

Источник

Читайте также:  Си шарп пример синтаксиса
Оцените статью