It's enough for JSON to get started with this article.

Posted by mo on Fri, 17 May 2019 04:22:47 +0200

What is JSON

JSON: JavaScript Object Notation

JSON is a grammar for storing and exchanging text information. Similar to XML.

JSON adopts a text format completely independent of any programming language, making JSON an ideal data exchange language S

Why do you need JSON

When it comes to JSON, we should compare it with XML. XML is also a means of storing and exchanging text information. So what's good about JSON?

JSON is smaller, faster and easier to parse than XML.

  • javaScript natively supports JSON and parses quickly
  • When XML is parsed into DOM objects, browsers [IE and fireFox] differ.
  • It's simpler to use JSON

 

 

Easier to create JavaScript objects

var p = {'city':['Beijing','Shanghai','Guangzhou','Shenzhen']};
for(var i=0;i<p.city.length;i++){
	document.write(p.city[i]+"<br/>");
}

JSON syntax

There are two kinds of interactive data between client and server.

  • array
  • object

So the data represented by JSON is either object or data.

JSON grammar is a subset of javaScript grammar, javaScript uses parentheses in [] to represent arrays, and {} braces to represent objects, and so does JSON.

JSON array:


	var employees = [
	{ "firstName":"Bill" , "lastName":"Gates" },
	{ "firstName":"George" , "lastName":"Bush" },
	{ "firstName":"Thomas" , "lastName": "Carter" }
	];

JSON object


        var obj = {

            age: 20,
            str: "zhongfucheng",
            method: function () {
                alert("I love learning.");
            }

        };

Of course, arrays can contain objects and arrays in objects.

Parsing JSON

JavaScript natively supports JSON. We can use eval() function to parse JSON and convert JSON text data into a JavaScript object.

        function test() {
			//When writing JOSN, remember to put a comma on it.
            var txt = "{a:123," +
                    "b:'zhongfucheng'}";

            //Using eval to parse JSON strings, you need to add ()
            var aa = eval("(" + txt + ")");
            alert(aa);

        }


 

Effect

 

 

Converting JavaBean s to JSON without frameworks

  • When using Struts 2, Struts 2 comes with components that can turn JavaBean objects and collections into JSON without splicing them together by ourselves.. This is very convenient.
  • When using Spring MVC, Spring MVC also supports converting JavaBean s to JSON

But we don't necessarily use frameworks for development. Therefore, we also have to learn how to use third-party libraries to convert JavaBean objects and collections into JSON.

Import Development Package

  • commons-io-2.0.1.jar
  • commons-lang-2.5.jar
  • commons-collections-3.1.jar
  • commons-beanutils-1.7.0.jar
  • ezmorph-1.0.3.jar
  • json-lib-2.1-jdk15.jar

Case code


package cn.itcast.javaee.js.bean2json;

import net.sf.json.JSONArray;

import java.util.*;

/**
 * Converting JavaBean objects / List or Set or Map objects to JSON using third-party tools 
 * @author AdminTC
 */
public class TestBean2Json {
	private static void javabean2json() {
		City city = new City(1,"Guangzhou");
		JSONArray jSONArray = JSONArray.fromObject(city);
		String jsonJAVA = jSONArray.toString();
		System.out.println(jsonJAVA);
		//[{id":1,"name":"Guangzhou"}]
	}
	private static void list2json() {
		List<City> cityList = new ArrayList<City>();
		cityList.add(new City(1,"Guangzhou"));
		cityList.add(new City(2,"Zhuhai"));
		JSONArray jSONArray = JSONArray.fromObject(cityList);
		String jsonJAVA = jSONArray.toString();
		System.out.println(jsonJAVA);
		//[{id":1,"name":"Guangzhou"}, {id":2,"name": "Zhuhai"}]
	}
	private static void set2json() {
		Set<City> citySet = new LinkedHashSet<City>();
		citySet.add(new City(1,"Guangzhou"));
		citySet.add(new City(2,"Zhuhai"));
		JSONArray jSONArray = JSONArray.fromObject(citySet);
		String jsonJAVA = jSONArray.toString();
		System.out.println(jsonJAVA);
		//[{id":1,"name":"Guangzhou"}, {id":2,"name": "Zhuhai"}]
	}
	private static void javabeanlist2json() {
		List<City> cityList = new ArrayList<City>();
		cityList.add(new City(1,"Zhongshan"));
		cityList.add(new City(2,"Foshan"));
		Province province = new Province(1,"Guangdong",cityList);
		
		JSONArray jSONArray = JSONArray.fromObject(province);
		String jsonJAVA = jSONArray.toString();
		System.out.println(jsonJAVA);
		/*
		  [
			 {
			  "id":1,
			  "name":"Guangdong "
			  "cityList":[{"id":1,"name":"Zhongshan"}, {id":2,"name": "Foshan"},
		     }
		  ]
		  */
	}
	private static void map2json() {
		
		List<City> cityList = new ArrayList<City>();
		cityList.add(new City(1,"Zhongshan"));
		cityList.add(new City(2,"Foshan"));
		
		Map<String,Object> map = new LinkedHashMap<String,Object>();
		map.put("total",cityList.size());//Represents the length of a collection
		map.put("rows",cityList);//rows represents a set
		
		JSONArray jSONArray = JSONArray.fromObject(map);
		String jsonJAVA = jSONArray.toString();
		System.out.println(jsonJAVA);
		//[{total": 2,"rows": [{id": 1, "name": "Zhongshan"}, {id":2,"name":"Foshan"}]
		
		jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1);
		System.out.println(jsonJAVA);
	}
	
}

Put the javaBena objects and collections to be parsed into JSON into the following code!

		JSONArray jSONArray = JSONArray.fromObject(map);

Whatever you put in, you return arrays.

summary

 

 

If there are any mistakes in the article, you are welcome to make corrections and communicate with each other. Students who are used to reading technical articles in Wechat can pay attention to Wechat Public Number: Java3y

Topics: JSON Javascript xml Struts