JSON (JavaScript Object Notation) study notes

JSON (JavaScript Object Notation ): It is a lightweight data exchange format
1. There are two structures for JSON construction: object and array
It is the structure of the key-value pair of {key: value, key: value,...}. In object-oriented languages, the key is the attribute of the object, and the value is the corresponding attribute value, so it is easy to understand. The value method is Object.key Gets the attribute value. The type of this attribute value can be a number, a string, an array, or an object.
2. Array: Array is the content expanded by square brackets "[]" in js. The data structure is ["java","javascript","vb",...]. The value method is the same as in all languages. Use index to get, the type of field value can be number, string, array, object.
Through the two structures of object and array, complex data structures can be combined.
2. Specific form
1. Object
(1) An object starts with "{" (left bracket) and ends with "}" (right bracket).
(2) Each "name" is followed by a ":" (colon)
(3) "'name/value' pairs" are separated by "," (comma)
Example : An object representing a person:
{
"name" : "Dahan",
"Age": 24
}
2. An array is an ordered collection of values.
(1) An array starts with "[" (left bracket) and ends with "]" (right bracket).
(2) Use ",


"Student" :
[
{"Name" : "Xiao Ming" , "Age" : 23},
{"Name" : "Dahan" , "Age" : 24}
]
}
Description: This Json object includes an array of students, And the values ​​in the student array are again two Json objects.
Having said these, I basically understand the data structure of json...

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java .util.LinkedHashMap; 
import java.util.List; 
import java.util.Map; 
 
import net.sf.ezmorph.bean.MorphDynaBean; 
import net.sf.json.JSONArray; 
import net.sf.json.JSONFunction; 
import net .sf.json.JSONObject; 
 
public class JsonTest { 
 
    public static void main(String args[]) { 
        //javaArray and json convert to each other 
        javaArrayAndJsonInterChange(); 
        System.out.println("--------------------- ----------------"); 
        //javaList and json convert to each other 
        javaListAndJsonInterChange(); 
        System.out.println("------------- ------------------------"); 
        //javaMpa and Json  convert to each
        other javaMapAndJsonInterChange(); 
        System.out.println("----- --------------------------------"); 
        //javaObject and jsonObject convert to each other 
        javaObjectAndJsonInterChange(); 
    } 
 
    /**
     * javaArray and json are converted to each other
     */ 
    public static void javaArrayAndJsonInterChange() { 
        // java to array 
        boolean[] boolArray = new boolean[] { true, false, true }; 
        JSONArray jsonArray = JSONArray.fromObject(boolArray); 
        String s = jsonArray.toString(); 
        System. out.println(s); 
 
        // Get the data in the array through json 
        String result = readJson("configdata"); 
 
        JSONArray jsonR = JSONArray.fromObject(result); 
        int size = jsonR.size(); 
        for (int i = 0; i < size; i++) { 
            System.out.println(jsonR.get(i)); 
        } 
    } 
 
    /**
     * javaList and json are converted to each other
     */ 
    public static void javaListAndJsonInterChange() { 
        List list = new ArrayList(); 
        list.add(new Integer(1)); 
        list.add(new Boolean(true)); 
        list.add(new Character('j')); 
        list.add(new char[] { 'j', 's', 'o', 'n' }); 
        list.add(null); 
        list.add("json"); 
        list.add(new String[] { "json", "-", "lib" }); 
 
        // list转JSONArray 
        JSONArray jsArr = JSONArray.fromObject(list); 
        System.out.println(jsArr.toString(4)); 
 
        // 从JSON串到JSONArray 
        jsArr = JSONArray.fromObject(jsArr.toString());          // print: json 
        // -- read from JSONArray 

        System.out.println(((JSONArray) jsArr.get(6)).get(0)); 
    } 
 
    /**
     * javaMpa和Json互转
     */ 
    public static void javaMapAndJsonInterChange() { 
        Map map = new LinkedHashMap(); 
        map.put("integer", new Integer(1)); 
        map.put("boolean", new Boolean(true)); 
        map.put("char", new Character('j')); 
        map.put("charArr", new char[] { 'j', 's', 'o', 'n' }); 
        // 注:不能以null为键名,否则运行报net.sf.json.JSONException: 
        // java.lang.NullPointerException: 
        // JSON keys must not be null nor the 'null' string. 
        map.put("nullAttr", null); 
 
        map.put("str", "json"); 
        map.put("strArr", new String[] { "json", "-", "lib" }); 
        map.put("jsonFunction", new JSONFunction(new String[] { "i" },"alert(i)")); 
        map.put("address", new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098")); 
        // map转JSONArray 
        JSONObject jsObj = JSONObject.fromObject(map); 
        System.out.println(jsObj.toString(4)); 
         
        // 从JSON串到JSONObject 
        jsObj = JSONObject.fromObject(jsObj.toString()); 
 
        //第一种方式:从JSONObject里读取 
        // print:json 
        System.out.println(jsObj.get("str")); 
        // print: address.city = Seattle, WA   
        System.out.println("address.city = " + ((JSONObject) jsObj.get("address")).get("city"));   
 
         
        //The second way: read data from dynamic beans, Since it can't be converted into a specific Bean, it doesn't feel very useful 
        . MorphDynaBean mdBean = (MorphDynaBean) JSONObject.toBean(jsObj); 
        // print: json 
        System.out.println(mdBean.get("str")); 
        //print: address.city = Seattle, WA   
        System.out.println("address.city = " + ((MorphDynaBean) mdBean.get("address")).get("city"));   
 
    } 
     
    /**
     * javaObject and jsonObject Interchange
     */ 
    public static void javaObjectAndJsonInterChange(){ 
        Address address=new Address("PO BOX 54534", "  Seattle, WA", 42452,"561-832-3180", "531-133-9098"); 
        //object转JSONObject 
        JSONObject jsObj = JSONObject.fromObject(address); 
        System.out.println(jsObj.toString(4)); 
         
        //JsonObject转java Object 
         
        Address addressResult=(Address) JSONObject.toBean(jsObj, Address.class); 
        System.out.println("address.city = "+ addressResult.getCity()); 
        System.out.println("address.street="+addressResult.getStreet()); 
        System.out.println("address.tel = "+ addressResult.getTel()); 
        System.out.println("address.telTwo="+addressResult.getTelTwo()); 
        System.out.println("address.zip="+addressResult.getZip()); 
    } 
 
    /**
     * 读取json文件
     * @param fileName 文件名,不需要后缀
     * @return
     */ 
    public static String readJson(String fileName) { 
        String result = null; 
        try { 
            File myFile = new File("./config/" + fileName + ".json"); 
            FileReader fr = new FileReader(myFile); 
            char[] contents = new char[(int) myFile.length()]; 
            fr.read(contents, 0, (int) myFile.length()); 
            result = new String(contents); 
            fr.close(); 
        } catch (FileNotFoundException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        return result; 
    } 
}

Author: Legendshop Liu Tao

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326221375&siteId=291194637