springMVC的controller層接收前端json數據


1.前端的操作:

  對象接收json數據方式:將所需要傳的數據轉化為json數據,並將這些數據以post方式傳到后台的controller層,然后controller層接收json數據,並且是以對象的形式進行接收。

 這里面是springmvc自動控制將這些數據轉化為對象,不需要輔助包fastjson。

  用Map<String,Object>接收json數據:需要使用fastjson包(前提json含有對象數據)。在看github項目的學習過程中,發現:封裝的對象中,可以有map<String,Object>類型,更加方便地接收參數,將json數據一一綁定到map映射中,方便我們對json數據操作哦。

2.代碼實現:

模擬前端傳過來的json數據

{
    "people": {
        "username": "Tom",
        "password": "123456",
        "sex": "男",
        "address": {
            "province": "安徽",
            "city": "蕪湖",
            "town": "天塹",
            "village": "小崗村"
        },
        "phones": [
            {
                "operator": "中國移動",
                "phoneNumber": "12345678901"
            },
            {
                "operator": "中國聯通",
                "phoneNumber": "09876543211"
            }
        ]
    }
}

Address.java

import lombok.Data;

@Data
public class Address {
    private String province;
    private String city;
    private String town;
    private String village;
}

Phone.java

import lombok.Data;

@Data
public class Phone {
    private String operator;
    private String phoneNumber;
}

People.java

import lombok.Data;

import java.util.List;

@Data
public class People {
    private String username;
    private String password;
    private String sex;
    private Address address;
    private List<Phone> phones;
}

controller類

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yyj.demo.pojo.Address;
import com.yyj.demo.pojo.People;
import com.yyj.demo.pojo.Phone;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/people")
public class PersonController {
    @RequestMapping("getPeople")
    public Map<String,Object> getPeople(@RequestBody People people){
        if(people == null){
            return null;
        }
        Map<String,Object> param = new HashMap<String, Object>();
        String s = people.getPhones().toString();
        System.out.println(s);
        param.put("people",people);
        return param;
    }
    @RequestMapping("getOtherPeople")
    public Map<String,Object> getOtherPeople(@RequestBody Map<String,Object> params){
        if(params == null){
            System.out.println("系統接收參數錯誤");
            return null;
        }
        Map<String,Object> map = new HashMap<>();
        People people = new People();
        people.setUsername(params.get("username").toString());
        people.setPassword(params.get("password").toString());
        people.setSex(params.get("sex").toString());
        people.setAddress(JSON.parseObject(JSONObject.toJSONString(params.get("address")),Address.class));
        people.setPhones((ArrayList<Phone>) params.get("phones"));
        map.put("people",people);
        return map;
    }
}
/*
{
    "username": "Tom",
    "password": "123456",
    "sex": "男",
    "address": {
        "province": "安徽",
        "city": "蕪湖",
        "town": "天塹",
        "village": "小崗村"
    },
    "phones": [{
            "operator": "中國移動",
            "phoneNumber": "12345678901"
        },
        {
            "operator": "中國聯通",
            "phoneNumber": "09876543211"
        }
    ]
}
 */

3.postman測試結果:

  對象接收方式:

 

 

   Map<String,Object>接收json數據

 

 

 4.第二種方式需要添加alibaba的fastjson依賴

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.47</version>
</dependency>

5.第二種實現方式遇到的各種坑:

  使用@ResquestBody Map<String,Object>接收前端json數據,json數據中有數組,我們不能用String[]去接收這個數組,要用ArrayList<String>去接收,原因如下:@RequsetBody會讀取request的body數據,之后會調用MappingJackson2HttpMessageConverter解析數據,會使用到ObjectMapper,之后this.objectMapper.readValue(inputMessage.getBody(), javaType);javaType是AbstractJackson2HttpMessageConverter中getJavaType優選出來可以解析context的類型.

  json數據中有對象數據存在時,我們不能單純的去直接用這個對象接收這個數據,會報錯的。報錯內容:java.util.LinkedHashMap cannot be cast to ******我的具體做法如下:我們可以接收的hashmap轉換為json,然后再次把這個json轉換為對應的對象。(如有更好的辦法,還望大佬在評論區告訴我一下)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM