Java的json得到我们想要的数据结构
第一步:首先我们要知道json就两种数据结构。
!!!第一种数据结构:对象用{ }表示
!!!第二种数据结构:数组用[ ]表示


所以我们先new Bar对象。


所以我们后面用的Arraylist


所以我们后面就是一个数组对象。(数组里面是对象)也就是ArrayList

然后set就ok了(都是在前面的对象数组里执行)





测试:


!!!总结:

这里我直接说逻辑我们怎么写:
首先我们发现其中最外面是一个[ ]是一个数组。而且是一个对象数组所以我们方法就要定义为ArrayList

- package com.example.demo5.controller;
-
-
-
- import com.example.demo5.pojo.Bar;
-
- import com.example.demo5.pojo.Series;
-
- import org.springframework.web.bind.annotation.*;
-
-
-
- import java.util.*;
-
-
-
- /**
- * 对象的属性里面嵌套数组,还有数组里面([]为数组,{}为对象)
- */
-
- @RestController
-
- @RequestMapping("/bar")
-
- public class BarController {
-
-
-
- @GetMapping
-
- public Bar bar() {
-
- Bar bar=new Bar();
-
- ArrayList
strings = new ArrayList(){{ -
- add("苹果");
-
- }};
-
- bar.setCategories(strings);
-
-
-
- ArrayList
series = new ArrayList(){{ -
- Series s = new Series();
-
- s.setName("手机品牌");
-
- s.setData(new ArrayList
() { -
- {
-
- add(1);
-
- add(2);
-
- add(3);
-
- }
-
- });
-
- add(s);
-
- }};
-
- bar.setSeries(series);
-
- return bar;
-
- }
-
- }
-
- package com.example.demo5.pojo;
-
-
-
- import lombok.Data;
-
-
-
- import java.util.List;
-
- import java.util.Map;
-
-
-
- @Data
-
- public class Bar {
-
- private List
categories; -
- private List
series; -
- }
-
-
-
- package com.example.demo5.pojo;
-
-
-
- import lombok.Data;
-
-
-
- import java.util.List;
-
-
-
- @Data
-
- public class Series {
-
- private String name;
-
- private List
data; -
- }
-
-
-
- package com.example.demo5.controller;
-
-
-
- import com.example.demo5.piepojo.Pie;
-
- import org.springframework.web.bind.annotation.GetMapping;
-
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import org.springframework.web.bind.annotation.RestController;
-
-
-
- import java.util.ArrayList;
-
-
-
- /**
- * 对象数组(本质是个数组(最外面是[]数组))(也就是多个对象)其中[]为数组。{}为对象
- */
-
- @RestController
-
- @RequestMapping("/pie")
-
- public class PieController {
-
- @GetMapping
-
- public ArrayList
pie(){ -
- ArrayList
list=new ArrayList<>(); -
- Pie pie = new Pie();
-
-
-
- pie.setName("苹果");
-
- pie.setValue(108370);
-
- pie.setUrl("http://www.baidu.com");
-
-
-
- Pie pie2 = new Pie();
-
- pie2.setName("华为");
-
- pie2.setValue(2934456);
-
- pie2.setUrl("http://www.baidu.com");
-
-
-
- list.add(pie);
-
- list.add(pie2);
-
-
-
- return list;
-
- }
-
-
-
-
-
- }
-
-
-
- package com.example.demo5.piepojo;
-
-
-
- import lombok.Data;
-
-
-
- @Data
-
- public class Pie {
-
- private String name;
-
- private Integer value;
-
- private String url;
-
- }