Getting Started with Java: Working with JSON-formatted data

Source: Internet
Author: User
Tags scalar

This section mainly explains:

1) JSON format data processing method

2) How to use the third-party toolkit

3) Java Collection data type

"Project Tasks"

Write a program that displays future weather information.

"Knowledge point Resolution"

In order to facilitate the analysis of the following code, the first need to master a few related knowledge.

1. What is JSON format data

Structurally, all the data that we see can eventually be decomposed into three types:

The first type is scalar (scalar), which is a single string (string) or number (numbers), such as "Beijing", a separate word. The second type is the sequence (sequence), which is a number of related data that are tied together in a certain order, also called an array or list, such as "Beijing, Shanghai." The third type is mapping (mapping), a name/value pair (Name/value), which has a name and a value corresponding to it, also known as hash (hash) or dictionary (dictionary), such as "Capital: Beijing".

JSON is a data format rule that gives a set of descriptive rules for the data of the above three structures, and the data that satisfies this rule is called JSON data.

The JSON rules are as follows:

1) The data is separated by commas (","). 2) The map is represented by a colon (":"). 3) a set (array) of side data is expressed in square brackets ("[]"). 4) The Set of Mappings (objects) are represented by curly braces ("{}"). 

The above four rules are all content in JSON format.

For example, the following sentence:

"Beijing's area is 16800 square kilometers, the resident population is 16 million people." The area of Shanghai is 6400 square kilometers, the resident population is 18 million. "

Written in JSON format:

[ {"city":"Beijing", "area": 16800, "Population":+), {"city":"Shanghai", "area": 6400, "Population" : 1800}]

If you know the structure of the data beforehand, the above wording can be further simplified:

[["Beijing", 16800,1600], ["Shanghai", 6400,1800]]

For more information about JSON data, please click to view

2. How to use JSON format data

In Java, for JSON-formatted data, it cannot be used directly, and it needs to be parsed first. This interpretation process involves converting any Java-formatted data into JSON-formatted data, or converting JSON-formatted data into Java objects. There are a number of third-party JSON data parsing toolkits available that provide very convenient operations that can be used directly into our programs without having to write code to parse the JSON yourself. In these JSON parsing tools, Json-lib is simpler to use, and here's a look at how to add the Json-lib Toolkit to your program.

First, Introduction

Json-lib package is mainly used to parse JSON data, in its official website http://www.json.org/on the detailed explanation, interested can go to study.

Ii. Download the jar dependency package

Here, for example, the package needs to rely on other toolkits for normal use, and in addition to importing the Json-lib-2.3.jar package, other dependent packages are imported into the Json-lib-2.3.jar package. All packages such as:

Here's the way to give: Http://pan.baidu.com/s/1kVIrdEf

Third, add the toolkit to the project

First, copy the jar to the project directory under the Myeclispe workspace! For example: My project is called Test, the workspace is D:\MyProjects so just copy the jar to D:\MyProjects\test\, and then, on MyEclipse project "test", right-click->build path-> Config build path, display the Librars tab, click Add Jars (before the Add, the last refresh refreshes, or you may not see your project name), add the above 6 packages one after another. After the addition is complete, the project structure is as follows:

After the addition is done, import the classes you want to use in the header of the program code that you want to use with the Json-lib tool.

The following example illustrates the use of the JSON tool

 Packagedatacollection;Importjava.util.ArrayList;Importjava.util.List;ImportNet.sf.json.JSONArray; Public classMainClass { Public Static voidMain (string[] args) {//TODO auto-generated Method StubList List =NewArrayList (); List.add ("First" ); List.add ("Second" ); Jsonarray Jsonarray=jsonarray.fromobject (list);      System.out.println (Jsonarray); }}

The code above converts the list of lists into a Jsonarray object that contains data in JSON format: ["First", "second"].

Jsonarray Jsonarray = Jsonarray.fromobject ("[' json ', ' is ', ' easy ']" );  System.out.println (Jsonarray);   // output results ["JSON", "is", "easy"]  

The code above is converting a string "[' json ', ' is ', ' easy ']" into a Jsonarray object that contains data such as: ["JSON", "is", "easy"]

 Packagedatacollection;Importjava.util.ArrayList;Importjava.util.List;ImportNet.sf.json.JSONObject; Public classMainClass { Public Static voidMain (string[] args) {//TODO auto-generated Method StubString json = "{bool:true,integer:1,string:\" json\ "}"; Jsonobject Jsonobject=Jsonobject.fromobject (JSON);    System.out.println (Jsonobject); }}

The code above converts a string "{Bool:true,integer:1,string:\" json\ "}" to a Jsonobject object that contains the data: {bool:true,integer:1,string:\ " Json\ "}

For more detailed usage of the Json-lib package, please click on the official website

 

Getting Started with Java: Working with JSON-formatted data

Related Article

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.