JAVA USES JSON for the data transfer example

  • 2020-05-30 20:18:24
  • OfStack

Recently I have been working on an WEB application based on JAVA Servlet and the corresponding Anroid application client.

Among them, in terms of interface access and data transmission, most of them use JSON object to manipulate and format data: JSON string is used to transfer data on the server side, and JSON is used to parse the received data on the front end of WEB or the client end of Android.

First, using JSON in JAVA requires the introduction of the org.json package and the corresponding JSON class in the program:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

Second, in the server-side Servlet class, you can use the following method to collect data and generate the corresponding JSON string

// The statement 1 a Hash Object and add the data 
Map params = new HashMap();

params.put("username", username);
params.put("user_json", user);

// The statement JSONArray Object and enter JSON string 
JSONArray array = JSONArray.fromObject(params);

In the front end of WEB, javascript can be used to parse JSON string directly. In the client end of Android, JSON class needs to be used to parse strings:

//@description:  Based on what you receive JSON String to parse the data and data objects contained in the string 

// The received JSON string 
String result = "[{\"username\": \"your name\", \"user_json\": {\"username\": \"your name\", \"nickname\": \"your nickname\"}}]";

// Generate from a string JSON object 
JSONArray resultArray = new JSONArray(result);
JSONObject resultObj = resultArray.optJSONObject(0);

// Get data item 
String username = resultObj.getString("username");

// Get data object 
JSONObject user = resultObj.getJSONObject("user_json");
String nickname = user.getString("nickname");

In fact, it mainly involves the conversion between the following centralized data types:

1. Convert String to JSON objects

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

// Don't forget to add it JSON Package: oh !
public class StringToJSON {
  public static void main(String[] args) throws JSONException{
    // define JSON string 
    String jsonStr = "{\"id\": 2," + 
        " \"title\": \"json title\", " + 
        "\"config\": {" +
          "\"width\": 34," +
          "\"height\": 35," +
        "}, \"data\": [" +
          "\"JAVA\", \"JavaScript\", \"PHP\"" +
    // Converted into JSONObject object 
    JSONObject jsonObj = new JSONObject(jsonStr);
    // from JSONObject Gets data from an object 
    JavaBean bean = new JavaBean();
    // Get by property name int Type of data ;
    // Get by property name String data ;
    // Get by property name JSONObject class 
    JSONObject config = jsonObj.getJSONObject("config");
    // Get by property name JSONArray An array of 
    JSONArray data = jsonObj.getJSONArray("data");
    for(int index = 0, length = data.length(); index < length; index++) {
      // Here in org.json.JSONArray I didn't find it in the object toArray Method, beg each net friend to give solution! 
//      bean.setLanguages(String[]);

class JavaBean{
  private int id ;
  private String title;
  private int width;
  private int height;
  private String[] languages;

    // The setters and accessors are omitted here 

2. JSON object is converted to String string

public static void main(String[] args) throws JSONException {
    // create JSONObject object 
    JSONObject json = new JSONObject();
    // to json Add data in 
    json.put("username", "wanglihong");
    json.put("height", 12.5);
    json.put("age", 24);
    // create JSONArray Array, and will json Add to array 
    JSONArray array = new JSONArray();
    // Convert to a string 
    String jsonStr = array.toString();

The final output is: [{" username ":" wanglihong ", "height" : 12.5, "age" : 24}]

3. Convert the collection to JSONArray objects

public static void main(String[] args)throws JSONException{
    // Initialize the ArrayList Collect and add data 
    List<String> list = new ArrayList<String>();
    // Initialize the HashMap Collection and add an array 
    Map map = new HashMap();
    map.put("bookname", "CSS3 In actual combat ");
    map.put("price", 69.0);
    // Initialize the JSONArray Object and add the data 
    JSONArray array = new JSONArray();
    // The generated JSON The string is: [["username","age","sex"],{"price":69,"bookname":"CSS3 In actual combat "}]

Related articles: