JSON summary and the actual JSON operation of the Fastjson package __js

Source: Internet
Author: User
Work, you need to deal with the other side of the system data exchange problems, using the method of invoking the remote interface, the data format to choose JSON, today to chat about JSON, the main analysis of the JSON data and Java bean transformation between the problem.
One, what is JSON
JSON, the full name is the JavaScript Object notation, Chinese translation is a kind of lightweight data interchange format, it is easy for developers to write and read, but also easy to generate and parse machine.
Two, JSON data structure
1, you can store objects (object), use the curly brace {} contains the key value pairs structure, the key must be a string type, value is any basic type or data structure.
2, you can store arrays (array), use the brackets [] to start, and comma, to split the elements.
3. You can store string type, number type (integer, floating-point type), Boolean (True, false), and null (you can first define an object as NULL when using NULL).
third, the grammar

1, the normal key value pairs.

{"Name": "Ogawa", "Age": "Gender": "Boy", "Hasgirlfriend": false}

2, storage objects.

{"Name": "Ogawa", "Age": "Gender": "Boy", "Hasgirlfriend": false}

3, storage array.

{"Name": "Ogawa", "Age": "Gender": "Boy", "Hasgirlfriend": false, "interest": ["Coding", "reading"]}

4, the object Addends group compound.

{"Name": "Ogawa", "Age": "Gender": "Boy", "Hasgirlfriend": false, "interest": ["Coding", "reading"]}

Iv. Preparatory work
1, development system: Win7 64-bit.
2, development environment: jdk1.8.
3, development language: java.
4, development tools: Eclipse.

5, Fastjson jar package: I am using the Maven pom.xml file configuration

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactid>fastjson</ artifactid>
    <version>1.2.4</version>
</dependency>

V. Use Ali's Fastjson toolkit to actually manipulate JSON

1. Building Entity Classes

public class Person {public String name;
	public int age;
	public String gender;
	public String interest;
	
	public Boolean hasgirlfriend; 
		Public person () {} public person (string name, int age, string gender, string interest, Boolean hasgirlfriend) {super ();
		THIS.name = name;
		This.age = age;
		This.gender = gender;
		This.interest = interest;
	This.hasgirlfriend = Hasgirlfriend;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	public int getage () {return age;
	public void Setage (int age) {this.age = age;
	Public String Getgender () {return gender;
	} public void Setgender (String gender) {This.gender = gender;
	Public String Getinterest () {return interest;
	} public void Setinterest (String interest) {this.interest = interest;
	public Boolean ishasgirlfriend () {return hasgirlfriend;
	} public void Sethasgirlfriend (Boolean hasgirlfriend) {this.hasgirlfriend = Hasgirlfriend; }
}
2, the Writing tool class.

Import Java.util.HashMap;

Import Java.util.Map;
Import Com.alibaba.fastjson.JSON;
Import Com.alibaba.fastjson.JSONArray;

Import Com.alibaba.fastjson.JSONObject;  public class Jsonutils {/** * Converts a JSON string to a JSON object * @param jsonstr JSON String * @return/public static Jsonobject
		Changestringtojson (String jsonstr) {jsonobject Jo = Json.parseobject (JSONSTR);
	return Jo; /** * Converts a JSON string array to a JSON array object * @param jsonstr JSON String * @return/public static Jsonarray Changestringtoarray (String jsonstr)
		{Jsonobject Jo = Json.parseobject (JSONSTR);
		if (!jo.containskey ("person")) {return null;
		String Strarray = jo.getstring ("person");
		Jsonarray ja = jsonarray.parsearray (strarray);
	Return ja; /** * Converts a JSON string to a Java Bean object * @param jsonstr JSON String * @return/public static person Changejsontobean (Stri
		ng Jsonstr) {Person of person = Json.parseobject (jsonstr, Person.class);
	return person; /** * Convert Java Bean objects to JSON objects * @param person java BeaN Object * @return/public static jsonobject Changebeantojson (person person) {Jsonobject Jo = (jsonobject) Json.tojson (
		person);
	return Jo; /** * Convert JSON string to MAP * @param jsonstr JSON String * @return/public static map<string,object> Changejsont
		OMap (String jsonstr) {map<string,object> Map = new hashmap<string,object> ();
		Jsonobject Jo = Json.parseobject (JSONSTR);
		For (String Str:jo.keySet ()) {map.put (str, jo.get (str));
	} return map; }
}
3, write test cases.
Package testDay02;

Import Java.util.Map;
Import Org.junit.After;
Import Org.junit.Before;

Import Org.junit.Test;
Import Com.alibaba.fastjson.JSONArray;

Import Com.alibaba.fastjson.JSONObject; Import day02.
Jsonutils; Import day02.
person; Import day02.
READXML;

Import junit.framework.*;
	public class TestUnit01 extends TestCase {protected long starttime;
	
	protected long endtime; public static final String Json_to_bean = "{" + "' name ': ' Ogawa '," + "' age ':" + "' Gender ': ' Boy '," + "' Hasgirl
	
	Friend ': false, "+" ' interest ': ' Coding ' "+"} "; public static String str = "{\ person\": {"+" \ "name\": \ "Ogawa 94\", "age\": 18,\ "gender\": \ "boy\", "+" \ "hasgirlfriend\"
	
	: false,\ "interest\": \ "coding\"} ";
	
	public static String Strarray = "{\ person\": ["+" {\ "name\": \ "Ogawa 94_2 number \"},{\ "name\": \ "Ogawa 94_3 number \"}]} ";
		@Before public void SetUp () throws Exception {this.starttime= system.currenttimemillis ();
	System.out.println ("========= begins testing ==========="); } @After Public VOID teardown () throws Exception {this.endtime = System.currenttimemillis ();
		System.out.println ("Test:" + (Endtime-starttime));
	System.out.println ("========= test over ===========");
		@Test public void Testchangepersontobean () {Person of person = Jsonutils.changejsontobean (Json_to_bean);
		SYSTEM.OUT.PRINTLN (person);
		System.out.println ("Name:" +person.getname ());
		System.out.println ("Age:" +person.getage ());
	System.out.println ("Sex:" +person.getgender ());
		@Test public void Testchangebeantojson () {Person of person = new person ();
		Person.setname ("Ogawa 94");
		Person.setage (18);
		Person.setgender ("Boy");
		Person.sethasgirlfriend (FALSE);
		Person.setinterest ("coding");
		Jsonobject Jo = Jsonutils.changebeantojson (person);
	System.out.println (Jo);
		@Test public void Testchagejsontomap () {map<string,object> Map = Jsonutils.changejsontomap (Json_to_bean);
	SYSTEM.OUT.PRINTLN (map); @Test public void Testchangestringtojson () {Jsonobject Jo = jsonutils.changestringTojson (str);
	System.out.println (Jo);
		@Test public void Testchangestringtoarray () {Jsonarray ja = jsonutils.changestringtoarray (strarray);
		System.out.println (JA);
	System.out.println (ja.get (0));
 }
	
}
4. Operation result

========= begins testing ===========
{"person": {"gender": "Boy", "interest": "Coding", "name": "Ogawa", "Hasgirlfriend": false , the "Age":}}
Test when: 965
========= test end ===========
========= start test ===========
{"name": "Ogawa", "gender" : "Boy", "Hasgirlfriend": false, "interest": "Coding", "age": When
test: 118 =========
test end =========== =====
= = = Start Test ===========
[{' Name ': ' Ogawa 94_2 number '},{' name ': ' Ogawa 94_3 #}]
{' name ': ' Ogawa 94_2 '}
Test: 5
= = = = = Test End ===========
========= start test ===========
day02. person@2fc14f68
Name: Ogawa
Age:
Sex: Boy
test:
========= Test End ===========
========= Start testing ===========
{gender=boy, interest=coding, Name= Ogawa, Hasgirlfriend=false, age=18} when
testing: 6
= = = = = Test End ===========

The article starts with my personal public number: Yue Le book. I like to share the songs I've heard along the way, the movies I've seen, the books I've read, the code I've been reading, the late meditation. Look forward to your attention.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.