Home > Java > javaTutorial > JAVA generates and parses parenthesized json data and its brief introduction

JAVA generates and parses parenthesized json data and its brief introduction

php是最好的语言
Release: 2018-08-02 11:35:34
Original
2130 people have browsed it

1. A brief introduction to json

1.1 json is the most popular and widely used data transmission format, referred to as JavaScript Object Notation, which was first used in JavaScript.

1.2 Give an example For example, the following is a json object named Wang Nima. He has two fans forming an array, one is called Xiao Wang and the other is named Xiao Nima:

{
      "name":"王尼玛",
      "fans":[{
            "name":"小王",
            "age":"7"
           },{
            "name":"小尼玛",
            "age":"10"
           }]
      }
Copy after login

2.json data generation and analysis

 2.1 There are several types of packages for json processing, such as open source jackson, Google Gson, and Alibaba's Fastjson. Gson is powerful, but Fastjson is faster. How to choose is a matter of opinion.

 2.2 I started here Use org.json. Later, in order to demonstrate the conversion of complex json to java beans, the powerful Gjson is imported. First, two maven dependencies are attached:

    <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.7</version>
        </dependency>
Copy after login

 2.3 Generation of json data, that is, conversion of various types to json. (String, map and java beans)

DemoCreateJson.java

import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by garfield on 2016/10/16.
 * 举三种创建json的例子
 */
public class DemoCreateJson {
    public static void main(String[] args) {
        StringCreateJson();
        mapCreateJson();
        beanCreateJson();
    }
    //String创建json
    /**
     * {
           "name":"王尼玛",
           "fans":[{
                 "name":"小王",
                 "age":"7"
                },{
                 "name":"小尼玛",
                 "age":"10"
                }]
           }
     */
    static void StringCreateJson(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","王尼玛");

        //粉丝是个数组,其实就是嵌套json
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("name","小王");
        jsonObject1.put("age",7);

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("name","小尼玛");
        jsonObject2.put("age",10);

        //从此处可以看出其实list和json也是互相转换的
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        jsonObjects.add(jsonObject1);
        jsonObjects.add(jsonObject2);
        jsonObject.put("fans",jsonObjects);

        System.out.println("jsonObject直接创建json:" + jsonObject);
    }
    //第二种方法,用map方式
    static void mapCreateJson(){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("name","王尼玛");
        Map<String,Object> map1 = new HashMap<String,Object>();
        map1.put("name","小王");
        map1.put("age",7);
        Map<String,Object> map2 = new HashMap<String,Object>();
        map2.put("name","小尼玛");
        map2.put("age",10);
        List<Map> jsonObjects = new ArrayList<Map>();
        jsonObjects.add(map1);
        jsonObjects.add(map2);
        map.put("fans",jsonObjects);
        System.out.println("集合中Map创建json对象:" + new JSONObject(map));
    }
    //第三种,也是比较常用的,用bean转换,(这里用的是map作为子json,如果必须要创建复杂bean对象,建议用Gjson操作)
    static void beanCreateJson(){
        Actor actor = new Actor();
        actor.setName("王尼玛");
        Map<String,Object> map1 = new HashMap<String,Object>();
        map1.put("name","小王");
        map1.put("age",7);
        Map<String,Object> map2 = new HashMap<String,Object>();
        map2.put("name","小尼玛");
        map2.put("age",10);
        List<Map> maps = new ArrayList<Map>();
        maps.add(map1);
        maps.add(map2);
        actor.setFans(maps);
        System.out.println("java bean创建json对象:" + new JSONObject(actor));
    }
}
Copy after login

2.3.1 The above class lacks basic beans

Actor.java

import java.util.List;
import java.util.Map;

/**
 * Created by garfield on 2016/10/16.
 */
public class Actor {
    private String name;
    private List<Map> fans;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Map> getFans() {
        return fans;
    }

    public void setFans(List<Map> fans) {
        this.fans = fans;
    }

}
Copy after login

2.4 json For parsing, two parsing methods are written here. Similarly, the second one is more commonly used, json to java bean

DemoParseJson.java

import com.google.gson.*;
import org.json.JSONObject;

import java.util.Map;

/**
 * Created by garfield on 2016/10/16.
 */
public class DemoParseJson {
    public static void main(String[] args) {
        String jsonString = "{\"fans\":[{\"name\":\"小王\",\"age\":7},{\"name\":\"小尼玛\",\"age\":10}],\"name\":\"王尼玛\"}";
        normalParse(jsonString);
        beanParse(jsonString);
    }
    static void normalParse(String jsonString){
        JSONObject jsonObject = new JSONObject(jsonString);
        //获取普通属性
        System.out.println("姓名:");
        System.out.println("  " + jsonObject.getString("name"));
        //获取数组
        System.out.println("粉丝:");
        for (Object fan : jsonObject.getJSONArray("fans")) {
            JSONObject object = (JSONObject)fan;
            System.out.println("  姓名:" + object.get("name") + ",年龄:" + object.get("age"));
        }
    }
    //org.json并不支持这种复杂的bean转换,所以这边又导入了gson的包
    static void beanParse(String jsonString){
        System.out.println("=========Gson解析=========");
        JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
        Actor actor = new Gson().fromJson(obj,Actor.class);
        System.out.println("姓名:");
        System.out.println("  " + obj.get("name"));
        System.out.println("粉丝:");
        for (Map map : actor.getFans()) {
            System.out.println("  姓名:" + map.get("name") + "年龄:" + map.get("age"));
        }
    }
}
Copy after login

2.4.1 By the way, the execution results are attached:

姓名:
  王尼玛
粉丝:
  姓名:小王,年龄:7
  姓名:小尼玛,年龄:10
=========Gson解析=========
姓名:
  "王尼玛"
粉丝:
  姓名:小王年龄7.0
  姓名:小尼玛年龄10.0
Copy after login

Related articles:

Detailed introduction to fastjson generation and parsing json data (serialization and deserialization data) in java

java uses FastJson to parse Json data

Related videos:

Comprehensive analysis of Java annotations

The above is the detailed content of JAVA generates and parses parenthesized json data and its brief introduction. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template