The method of using JSON in JSON for network data interaction
The method of using JSON in JSON for network data interaction
Introduction:
JSON (JavaScript Object Notation) is a lightweight data exchange format that is widely used in data transmission and storage in Web applications.The use of JSON in JSON for network data interaction can help achieve data exchange and communication between different systems.This article will introduce the method of using JSON in JSON for network data interaction, as well as the corresponding code examples.
1. Import json library
Before using JSON for network data interaction, we first need to import the corresponding JSON library.There are currently many JSON libraries commonly used in Java, such as GSON, Jackson, Fastjson, etc.Taking the GSON library as an example, we can add GSON's dependencies in the project, or manually download the GSON jar file and import it into the project.
2. Serialization and deepening serialization
The core of using JSON for network data interaction is to convert the Java object into a string (that is, serialize) in the JSON format, and the string of the JSON format into a Java object (that is, the derivative).
Example code 1: serialized Java object is JSON string
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
// Create a Java object
Person Person = New Person ("Zhang San", 25);
// Create GSON objects
Gson gson = new Gson();
// Sequence java objects to JSON string
String json = gson.toJson(person);
// Output json string
System.out.println(json);
}
}
// Define a Person class
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Example Code 2: Turn the JSON string back -sequentially into the Java object
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
// Define a json string
String json = "{\" name \ ": \" Zhang San \ ", \" Age \ ": 25}";
// Create GSON objects
Gson gson = new Gson();
// Turn the JSON string back -sequencing into the Java object
Person person = gson.fromJson(json, Person.class);
// Output the attribute value of the java object
System.out.println
System.out.println ("age:" + Person.getage ());
}
}
// Define a Person class
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
3. Send and receive JSON data
Common scenarios using JSON for network data interaction are sending and receiving JSON data.When sending JSON data, we need to send the JSON string as the request body to the server; when receiving JSON data, we need to receive the JSON string from the server and convert it to the Java object.
Example Code 3: Send POST request and send json data
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Define the target URL
URL url = new URL("http://example.com/api");
// Create HTTPURLCONNECTION object
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method as post
connection.setRequestMethod("POST");
// Set the request head information
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
// Set the allowable output
connection.setDoOutput(true);
// Create a json string
String json = "{\" name \ ": \" Zhang San \ ", \" Age \ ": 25}";
// Convert json string to byte array
byte[] jsonBytes = json.getBytes("UTF-8");
// Get output stream
OutputStream outputStream = connection.getOutputStream();
// Send json data
outputStream.write(jsonBytes);
outputStream.flush();
// Turn off the output stream
outputStream.close();
// Get the response code
int responseCode = connection.getResponseCode();
// Output response code
System.out.println ("response code:" + responsecode);
// Turn off the connection
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example code 4: JSON data returned by the server
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
// Define the target URL
URL url = new URL("http://example.com/api");
// Create HTTPURLCONNECTION object
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to get
connection.setRequestMethod("GET");
// Set the request head information
connection.setRequestProperty("Accept", "application/json");
// Get the response code
int responseCode = connection.getResponseCode();
// Output response code
System.out.println ("response code:" + responsecode);
// Read the response content
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// Turn off IO stream
reader.close();
// Output response content
System.out.println ("Response content:" + response.tostring ());
// Turn off the connection
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Summarize:
This article introduces the method of using JSON in JSON for network data interaction.First, we need to import the JSON library, such as GSON.Then, we learned how to sequence the Java object into a JSON string and the series of the JSON strings into the Java object.Finally, by sending and receiving the example code of JSON data, we show the complete process of how to use JSON for network data interaction.Mastering these methods can help achieve data exchange and communication between different systems.