【Spring Boot】请求参数传json对象,后端采用(map)CRUD案例(101)

8 篇文章 0 订阅

请求参数传json对象,后端采用(map)接收的前提条件:

1.Spring Boot 的Controller接受参数采用:@RequestBody
2.需要一个Json工具类,将json数据转成Map;

工具类:Json转Map


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.PropertyUtils;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

	/**
     * 。
     * (1) 使用泛型方法:把json字符串转换为相应的JavaBean对象;
     *     转换为普通JavaBean:readValue(json,Student.class);
     * (2) List Map转换List 对象:如List<Student>,将第二个参数传递为Student;
     * (3) List 对象转换List Map:
     *     [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List;
     *
     * @param jsonStr
     * @param valueType
     * @return
     * 
     */

public final class JsonUtils {

    private static ObjectMapper objectMapper;

    /**
     * (1) 使用泛型方法:把json字符串转换为相应的JavaBean对象;
     *     转换为普通JavaBean:readValue(json,Student.class);
     */
    public static <T> T readValue(String jsonStr, Class<T> valueType) throws Exception {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        return objectMapper.readValue(jsonStr, valueType);
    }

    /**
     *(2).List Map转换List 对象:如List<Student>,将第二个参数传递为Student对象;
     *    map转换为bean
     */
    public static Object mapToObject(Map<String, String> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;
        Object obj = beanClass.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            Method setter = property.getWriteMethod();
            if (setter != null) {
                setter.invoke(obj, map.get(property.getName()));
            }
        }
        return obj;
    }
	
	/**
	 *(3).List 对象转换List Map:
	 *    [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List;
     *    bean转换为map
     */
    public static <T> List<Map<String, Object>> listConvert(List<T> list){
        List<Map<String, Object>> list_map = new ArrayList<Map<String, Object>>();
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(item ->{
                Map<String, Object> map = null;
                try {
                    map = PropertyUtils.describe(item);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException(e);
                }
                list_map.add(map);
            });
        }
        return list_map;
    }
}

Controller类:@RequestBody
备注:为了便于测试:Controller类只写了一个接口(实际开发可不要这样写噢)


	 *
     * 请求参数传递json数据:json对象(map)
     *
     */
    @PostMapping(value = "/addTest")
    @AuthInterceptor("mg:get:addTest")
    public Result addTest(@RequestBody String param) {
        try {
            Map<String, Object> paramMap = JsonUtils.readValue(param, Map.class);
            return xxxListService.addTest(paramMap);
        } catch (Exception e) {
            log.error("Controller addTest is error===:" + e.getMessage(), e);
            return Result.failure("测试成功");
        }
    }
    

Service类:

	Result addTest(Map<String, Object> paramMap);

ServiceImpl类:


	@Override
    public Result addTest(Map<String, Object> paramMap) {
        List<Map<String, Object>> res = new ArrayList<>();
        String interfaceType = String.valueOf(paramMap.get("interfaceType"));
        if(interfaceType.equals("add")){
            xxxListMapper.addTest(paramMap);
        }
        else if(interfaceType.equals("del")){
            xxxListMapper.delTest(paramMap);
        }
        else if(interfaceType.equals("modify")){
            xxxListMapper.modifyTest(paramMap);
        }
        else if(interfaceType.equals("sel")){
            res = xxxListMapper.selTest(paramMap);
        }
        return Result.success().result(res);
    }
    

Mapper类:


	//新增
    void addTest(Map<String, Object> paramMap);
    //删除
    void delTest(Map<String, Object> paramMap);
    //修改
    void modifyTest(Map<String, Object> paramMap);
    //查询
    List<Map<String, Object>> selTest(Map<String, Object> paramMap);
    

Mapper.xml类


	<!-- 新增 -->
    <insert id="addTest" parameterType="map">
        INSERT IGNORE INTO xxx_other_list_dic
        (dicNameFirst,dicValueFirst,dicNameSecond,dicValueSecond,dicType,isEnable)
        VALUES
        (#{dicNameFirst},#{dicValueFirst},#{dicNameSecond},#{dicValueSecond},#{dicType},#{isEnable})
    </insert>
    <!-- 删除 -->
    <select id="delTest" parameterType="map">
        delete
        FROM xxx_other_list_dic where
        <if test = "null != seqId and '' != seqId">
            seqId = #{seqId}
        </if>
    </select>
    <!-- 修改 -->
    <update id="modifyTest" parameterType="map">
        update xxx_other_list_dic
        <set>
            <if test = "null != sortId and '' != sortId">
                sortId = #{sortId},
            </if>
            <if test = "null != isEnable and '' != isEnable">
                isEnable = #{isEnable}
            </if>
        </set>
        where
        <if test = "null != seqId and '' != seqId">
            seqId = #{seqId}
        </if>
    </update>
    <!-- 查询 -->
    <select id="selTest" parameterType="map" resultType="map">
        SELECT *
        FROM xxx_other_list_dic where 1 = 1
        <if test="null != dicNameFirst and '' != dicNameFirst">
            and dicNameFirst = #{dicNameFirst}
        </if>
        <if test="null != dicValueFirst and '' != dicValueFirst">
            and dicValueFirst = #{dicValueFirst}
        </if>
        <if test="null != dicNameSecond and '' != dicNameSecond">
            and dicNameSecond = #{dicNameSecond}
        </if>
        <if test="null != dicValueSecond and '' != dicValueSecond">
            and dicValueSecond = #{dicValueSecond}
        </if>
        <if test="null != dicType and '' != dicType">
            and dicType = #{dicType}
        </if>
        <if test="null != isEnable and '' != isEnable">
            and isEnable = #{isEnable}
        </if>
        order by sortId
    </select>
    

Postman 接口测试:
新增:
在这里插入图片描述
在这里插入图片描述
修改:
在这里插入图片描述
在这里插入图片描述
查询:
在这里插入图片描述
删除:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用Spring Boot中的JPA(Java Persistence API)实现将JSON数据写入MySQL数据库。JPA提供了一种简单的方式来管理对象关系映射(ORM),即将Java对象映射到关系型数据库中的表。 以下是一个简单的示例: 1. 创建一个实体类,用于映射JSON数据到数据库表中的字段。 ```java @Entity @Table(name = "person") public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // getters and setters } ``` 2. 创建一个Spring Data JPA repository接口,用于定义CRUD操作。 ```java @Repository public interface PersonRepository extends JpaRepository<Person, Long> { } ``` 3. 在Controller中获取JSON数据,并将其转换为Person对象,然后使用PersonRepository将其保存到数据库中。 ```java @RestController @RequestMapping("/person") public class PersonController { @Autowired private PersonRepository personRepository; @PostMapping("/save") public void savePerson(@RequestBody Person person) { personRepository.save(person); } } ``` 这里假设JSON数据的格式与Person类的属性相匹配。如果不匹配,可以使用Jackson库进行转换。 另外,需要在application.properties文件中配置MySQL数据库连接信息,例如: ``` spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=myusername spring.datasource.password=mypassword spring.datasource.driver-class-name=com.mysql.jdbc.Driver ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KevinDuc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值