尽管此 JSON 有数据,但方法返回 JSON“empty:false”

Posted

技术标签:

【中文标题】尽管此 JSON 有数据,但方法返回 JSON“empty:false”【英文标题】:Method returning JSON "empty:false" although this JSON has data 【发布时间】:2019-01-29 21:27:36 【问题描述】:

我有 java Spring Boot 应用程序。在控制台 json 中有数据(但顺序错误?),当我将其转换为字符串时,我可以得到它,但无法返回 JSONObject,POSTman 显示 "empty":false

我的控制器 包 com.example.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.dao.SeriaDao;
import com.example.model.Seria;


@RestController
public class WebController 

    @Autowired
    SeriaDao sed;


    @GetMapping("/tabelka")
    public List<Seria> showTable()
    
        return sed.findAll();
    

    @GetMapping("/pgTabelka")
    public JSONObject pgTable(HttpServletRequest request)
    
        int draw = 0;
        int start = 0;
        int length = 10;

        JSONObject json = new JSONObject();
        if(request.getParameter("draw")!=null)
            draw = Integer.parseInt(request.getParameter("draw"));
        if(request.getParameter("start")!=null)
            start = Integer.parseInt(request.getParameter("start"));
        if(request.getParameter("length")!=null)
            length = Integer.parseInt(request.getParameter("length"));
        int totalRecords = sed.recordsTotal();

        List<Seria> serie = sed.findPart(start, length);

        try 
            json.put("draw", ++draw);
            json.put("recordsTotal", totalRecords);
            json.put("recordsFiltered", totalRecords);
            json.put("data", serie);
         catch (JSONException e) 
            e.printStackTrace();
        
        System.out.println(json);

        return json;
    

我必须添加什么以及为什么我不能像我想要的那样获得 json?

PS。控制台返回的json:


  "recordsFiltered": 488,
  "data": [
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "$ per Week",
      "file": "SMU48185800500000011.csv",
      "cassid": "1d2e556b-031e-4c6f-aec4-981c4e907324",
      "name": "Average Weekly Earnings of All Employees: Total Private in Corpus Christi, TX (MSA)",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-01-09T00:50:01",
      "id": 41,
      "datefrom": "2006-12-31",
      "categoryid": 3,
      "frequency": 5
    ,
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "Index 2015=100",
      "file": "CP0910CYM086NEST.csv",
      "cassid": "6df5b8d5-ec39-4860-930f-a8b355cce37a",
      "name": "Harmonized Index of Consumer Prices: Audio-Visual, Photographic, and Information Processing Equipment for Cyprus",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-02-16T11:35:04",
      "id": 42,
      "datefrom": "1995-12-31",
      "categoryid": 3,
      "frequency": 5
    ,
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "$ per Week",
      "file": "SMU48185800500000011A.csv",
      "cassid": "c3bad2a6-7ad5-4091-846b-f84e9b9f7b50",
      "name": "Average Weekly Earnings of All Employees: Total Private in Corpus Christi, TX (MSA)",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-02-16T11:32:01",
      "id": 43,
      "datefrom": "2006-12-31",
      "categoryid": 3,
      "frequency": 8
    ,
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "Index 2015=100",
      "file": "CP0910CZM086NEST.csv",
      "cassid": "84483d95-d914-45ab-a87a-8c063bfc6d0f",
      "name": "Harmonized Index of Consumer Prices: Audio-Visual, Photographic, and Information Processing Equipment for Czech Republic",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-02-16T11:35:04",
      "id": 44,
      "datefrom": "1999-11-30",
      "categoryid": 3,
      "frequency": 5
    ,
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "$ per Week",
      "file": "SMU41187000500000011SA.csv",
      "cassid": "285056e3-94ce-4266-98b4-ddf32602c0c2",
      "name": "Average Weekly Earnings of All Employees: Total Private in Corvallis, OR (MSA)",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-01-09T00:50:01",
      "id": 45,
      "datefrom": "2006-12-31",
      "categoryid": 3,
      "frequency": 5
    ,
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "Index 2015=100",
      "file": "CP0910DKM086NEST.csv",
      "cassid": "9798eadf-1503-48a5-91e3-cad5852db745",
      "name": "Harmonized Index of Consumer Prices: Audio-Visual, Photographic, and Information Processing Equipment for Denmark",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-02-16T11:35:04",
      "id": 46,
      "datefrom": "1995-12-31",
      "categoryid": 3,
      "frequency": 5
    ,
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "$ per Week",
      "file": "SMU41187000500000011.csv",
      "cassid": "d4b22376-2f84-404f-a175-c04ad8ced5a5",
      "name": "Average Weekly Earnings of All Employees: Total Private in Corvallis, OR (MSA)",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-01-09T00:50:01",
      "id": 47,
      "datefrom": "2006-12-31",
      "categoryid": 3,
      "frequency": 5
    ,
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "Index 2015=100",
      "file": "CP0910EEM086NEST.csv",
      "cassid": "72880ba0-722e-46bb-98f4-7d388d217c26",
      "name": "Harmonized Index of Consumer Prices: Audio-Visual, Photographic, and Information Processing Equipment for Estonia",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-02-16T11:35:04",
      "id": 48,
      "datefrom": "1995-12-31",
      "categoryid": 3,
      "frequency": 5
    ,
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "$ per Week",
      "file": "SMU41187000500000011A.csv",
      "cassid": "03fdf50e-9cd9-483b-aecf-1a0a9e93fa4d",
      "name": "Average Weekly Earnings of All Employees: Total Private in Corvallis, OR (MSA)",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-02-16T11:32:01",
      "id": 49,
      "datefrom": "2006-12-31",
      "categoryid": 3,
      "frequency": 8
    ,
    
      "feed": "Macroeconomic_And_Major_Markets",
      "unit": "Index 2005=100",
      "file": "CP0910EZ17M086NEST.csv",
      "cassid": "2943c0f2-ad55-4ec4-98d0-70db25deaefc",
      "name": "Harmonized Index of Consumer Prices: Audio-Visual, Photographic, and Information Processing Equipment for Euro area (17 countries) (DISCONTINUED)",
      "createdate": "2016-10-15T23:38:49",
      "changedate": "2017-02-16T11:35:04",
      "id": 50,
      "datefrom": "1995-12-31",
      "categoryid": 3,
      "frequency": 5
    
  ],
  "draw": 1,
  "recordsTotal": 488

【问题讨论】:

我建议使用 Jackson 进行 JSON 转换。您无需编写此类代码或担心 JSON 字段排序。 Spring Boot 默认包含 Jackson。 你应该返回 json.toString() 而不是 JSONObject @SimonMartinelli 我试过了,但我需要 JSON 作为回报,因为我使用 DataTables 插件,并且数据应该以 JSON 类型发送给它... 但是如果你返回一个字符串,你会在邮递员中看到正确的 JSON 吗? @SimonMartinelli 然后我看到了文本 【参考方案1】:

Spring boot 使用 jackson 作为默认序列化程序,您正在尝试返回 JSONObject 本身。 Jackson 不知道如何序列化。

如果你想返回动态 json,你可以使用 Map 如下:

@GetMapping("/pgTabelka")
public Map<String, Object> pgTable(HttpServletRequest request)

    Map<String, Object> json = new HashMap();

    int draw = 0;
    int start = 0;
    int length = 10;

    if(request.getParameter("draw")!=null)
        draw = Integer.parseInt(request.getParameter("draw"));
    if(request.getParameter("start")!=null)
        start = Integer.parseInt(request.getParameter("start"));
    if(request.getParameter("length")!=null)
        length = Integer.parseInt(request.getParameter("length"));
    int totalRecords = sed.recordsTotal();

    List<Seria> serie = sed.findPart(start, length);

    json.put("draw", ++draw);
    json.put("recordsTotal", totalRecords);
    json.put("recordsFiltered", totalRecords);
    json.put("data", serie);

    return json;

或者你可以创建一个类来代表你的 json 结构并返回你的自定义数据类作为你的响应,spring 会为你处理剩下的。

@GetMapping("/pgTabelka")
public YourJsonDataClass pgTable(HttpServletRequest request)

    ...

    YourJsonDataClass json = new YourJsonDataClass();
    json.setDraw(++draw);
    json.setRecordsTotal(totalRecords);
    json.setRecordsFiltered(totalRecords);
    json.setData(serie);

    return json;

【讨论】:

谢谢!有用。但我还有一个问题......为什么变量的顺序不是 draw->recordsTotal->recordsFiltered->data ?【参考方案2】:

使用 HashMap 代替 JSONObject

List<HashMap<String, String>> myList = new ArrayList<HashMap<String, String>>();

HashMap<String, String> map = new HashMap<>();

map.put(key, value);

myList.add(map);

如果你有一个 ResultSet,你可以通过 rs 循环这段代码。 值得注意的是,如果你的 HashMap 有重复的键,你将不得不使用 Multimap,因为 HashMap 不允许重复的键

Multimap<String, String> map = ArrayListMultimap.create();
map.put(key1, "value1");
map.put(key1, "value2");
map.put(key2, "value3");

【讨论】:

【参考方案3】:

使用泛型类型ResponseEntity&lt;?&gt; 结合json.toString() 可以解决问题。

    @ResponseBody
    public ResponseEntity<?> create(@RequestBody User user) 
        return ResponseEntity.status(HttpStatus.OK).body(json.toString());
    

【讨论】:

【参考方案4】:

我收到这个错误是因为我写了

JSONObject j1 = method()
JSONObject j2 = new JSONObject(j1)

【讨论】:

以上是关于尽管此 JSON 有数据,但方法返回 JSON“empty:false”的主要内容,如果未能解决你的问题,请参考以下文章

路由器处理程序返回一个对象数组,但客户端没有在 json 中获取它们,尽管响应为 200 状态

如何递归处理 JSON 数据并从函数返回处理后的 JSON?

无法安装 Composer:尽管安装了 php5-json,但缺少 json 扩展

Afnetworking 返回 null json 尽管它是有效的

XMLHttpRequest下载文件方法中添加处理服务器返回json格式的错误提示信息

asp页面从数据库查询结果后 怎么返回为json格式