Three ways of analyzing JSON based on java

  • 2020-05-27 04:46:20
  • OfStack

This paper analyzes three ways to parse JSON based on java. I will share it with you for your reference as follows:

1. What is JSON?

JSON is a data structure that replaces XML. Compared with xml, JSON is smaller but not less powerful in terms of description.

JSON is just a string of strings except that the element is annotated with a particular notation.

{} double brackets represent objects
The [] brackets represent an array
"" inside the double quotation marks are attributes or values
: the colon indicates that the latter is the value of the former (this value can be a string, a number, or another array or object)

So {"name": "Michael"} can be interpreted as an object containing name as Michael

And [{" name ":" Michael "}, {" name ":" Jerry}] that contains two arrays of objects

Of course, you can also use {"name":["Michael","Jerry"]} to simplify part 1 above, which is an object with an array of name

2. Traditional JSON parsing of JSON parsing

1. Generate json string


public static String createJsonString(String key, Object value) {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(key, value);
    return jsonObject.toString();
}

2. Parse the JSON string

There are three cases, 1 JavaBean, 1 List array, and 1 List array nested within Map:


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.android.myjson.domain.Person;
/**
 *  Complete the json Data parsing 
 *
 */
public class JsonTools {
  public static Person getPerson(String key, String jsonString) {
    Person person = new Person();
    try {
      JSONObject jsonObject = new JSONObject(jsonString);
      JSONObject personObject = jsonObject.getJSONObject("person");
      person.setId(personObject.getInt("id"));
      person.setName(personObject.getString("name"));
      person.setAddress(personObject.getString("address"));
    } catch (Exception e) {
      // TODO: handle exception
    }
    return person;
  }
  public static List getPersons(String key, String jsonString) {
    List list = new ArrayList();
    try {
      JSONObject jsonObject = new JSONObject(jsonString);
      //  return json An array of 
      JSONArray jsonArray = jsonObject.getJSONArray(key);
      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject2 = jsonArray.getJSONObject(i);
        Person person = new Person();
        person.setId(jsonObject2.getInt("id"));
        person.setName(jsonObject2.getString("name"));
        person.setAddress(jsonObject2.getString("address"));
        list.add(person);
      }
    } catch (Exception e) {
      // TODO: handle exception
    }
    return list;
  }
  public static List getList(String key, String jsonString) {
    List list = new ArrayList();
    try {
      JSONObject jsonObject = new JSONObject(jsonString);
      JSONArray jsonArray = jsonObject.getJSONArray(key);
      for (int i = 0; i < jsonArray.length(); i++) {
        String msg = jsonArray.getString(i);
        list.add(msg);
      }
    } catch (Exception e) {
      // TODO: handle exception
    }
    return list;
  }
  public static List> listKeyMaps(String key,
      String jsonString) {
    List> list = new ArrayList>();
    try {
      JSONObject jsonObject = new JSONObject(jsonString);
      JSONArray jsonArray = jsonObject.getJSONArray(key);
      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject2 = jsonArray.getJSONObject(i);
        Map map = new HashMap();
        Iterator iterator = jsonObject2.keys();
        while (iterator.hasNext()) {
          String json_key = iterator.next();
          Object json_value = jsonObject2.get(json_key);
          if (json_value == null) {
            json_value = "";
          }
          map.put(json_key, json_value);
        }
        list.add(map);
      }
    } catch (Exception e) {
      // TODO: handle exception
    }
    return list;
  }
}

3. GSON analyzed by JSON

1. Generate JSON string


import com.google.gson.Gson;
public class JsonUtils {
  public static String createJsonObject(Object obj) {
    Gson gson = new Gson();
    String str = gson.toJson(obj);
    return str;
  }
}

2. Parse JSON


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
;
public class GsonTools {
  public GsonTools() {
    // TODO Auto-generated constructor stub
  }
  /**
   * @param
   * @param jsonString
   * @param cls
   * @return
   */
  public static T getPerson(String jsonString, Class cls) {
    T t = null;
    try {
      Gson gson = new Gson();
      t = gson.fromJson(jsonString, cls);
    } catch (Exception e) {
      // TODO: handle exception
    }
    return t;
  }
  /**
   *  use Gson parsing  List
   *
   * @param
   * @param jsonString
   * @param cls
   * @return
   */
  public static List getPersons(String jsonString, Class cls) {
    List list = new ArrayList();
    try {
      Gson gson = new Gson();
      list = gson.fromJson(jsonString, new TypeToken>() {
      }.getType());
    } catch (Exception e) {
    }
    return list;
  }
  /**
   * @param jsonString
   * @return
   */
  public static List getList(String jsonString) {
    List list = new ArrayList();
    try {
      Gson gson = new Gson();
      list = gson.fromJson(jsonString, new TypeToken>() {
      }.getType());
    } catch (Exception e) {
      // TODO: handle exception
    }
    return list;
  }
  public static List> listKeyMaps(String jsonString) {
    List> list = new ArrayList>();
    try {
      Gson gson = new Gson();
      list = gson.fromJson(jsonString,
          new TypeToken>>() {
          }.getType());
    } catch (Exception e) {
      // TODO: handle exception
    }
    return list;
  }
}

4. FastJSON for JSON analysis


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
public class JsonTool {
  public static T getPerson(String jsonstring, Class cls) {
    T t = null;
    try {
      t = JSON.parseObject(jsonstring, cls);
    } catch (Exception e) {
      // TODO: handle exception
    }
    return t;
  }
  public static List getPersonList(String jsonstring, Class cls) {
    List list = new ArrayList();
    try {
      list = JSON.parseArray(jsonstring, cls);
    } catch (Exception e) {
      // TODO: handle exception
    }
    return list;
  }
  public static List> getPersonListMap1(
      String jsonstring) {
    List> list = new ArrayList>();
    try {
      list = JSON.parseObject(jsonstring,
          new TypeReference>>() {
          }.getType());
    } catch (Exception e) {
      // TODO: handle exception
    }
    return list;
  }
}

Conclusion:

For mobile devices, JSON, especially in the case of poor network environment and traffic restrictions, will save more traffic and be more efficient than the data transmission in XML format. Of the three parsing methods, FastJson is the most efficient and is recommended.

PS: for the operation of json, here are some useful json online tools for your reference:

Online JSON code inspection, inspection, beautification and formatting tools:
http://tools.ofstack.com/code/json

JSON online formatting tool:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautification/compression/editing/conversion tools:
http://tools.ofstack.com/code/jsoncodeformat

Online json compression/escape tool:
http://tools.ofstack.com/code/json_yasuo_trans

C language style /HTML/CSS/json code formatting beautification tool:
http://tools.ofstack.com/code/ccode_html_css_json

I hope this article is helpful for you to design java program.


Related articles: