How to use JSON format in Java to store and transmit data
Use JSON format in Java to store and transmit data
In Java, we can use the JavaScript Object Notation format to store and transmit data.JSON is a lightweight data exchange format that is easy to read and write, and can be parsed and generated in different programming languages.
1. Import json library
To use JSON format in Java, we first need to import related JSON libraries.There are many JSON libraries that can be used, the most popular of which is Google's GSON library and Jackson library.Here we use the GSON library as an example. You can import the following dependency items to your Maven configuration file to import the GSON library:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
2. Convert the object to JSON string
To convert the Java object to the JSON string, we need to create a corresponding Java class, and use the tojson method of the GSON library to convert the object to the JSON string.For example, suppose we have a Java class called Person:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// omit the getter and setter method
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Below is a sample code that converts the PERSON object to a JSON string:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
Person Person = New Person ("Zhang San", 25);
Gson gson = new Gson();
String json = gson.toJson(person);
System.out.println(json);
}
}
The output result will be a JSON string that indicates the Person object: {"name": "Zhang San", "Age": 25}
3. Convert json string to object
Similarly, we can use the GSON library to convert JSON string back to the Java object.By using the FROMJSON method to pass the type of JSON string and target Java class to it, the GSON library will automatically convert the JSON string into the corresponding Java object.The following is an example code:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String json = "{\" name \ ": \" Zhang San \ ", \" Age \ ": 25}";
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
System.out.println(person);
}
}
The output result will be a string that indicates the Person object: Person {name = 'Zhang San', Age = 25}
4. Use JSON as a data transmission format
In Java, we can also use the JSON format as the data transmission format.For example, we can use Java's URL and HTTPURLCONNECTION classes to send and receive JSON data.The following is an example code that sends a post request and receives JSON response:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
// Set the request header
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
// Set the request body
String requestbody = "{\" name \ ": \" Zhang San \ ", \" Age \ ": 25}";
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
// Get the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Analysis response
String jsonResponse = response.toString();
System.out.println(jsonResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The above code sample sends a post request to send the request body containing JSON data to "http://example.com/api".It then received and parsed the JSON response and printed the response results on the console.
This is the basic method of storing and transmission data in JSON format in Java.You can use other functions of the JSON library according to actual needs, such as processing nested objects, array and date.