How to convert the Json field in the database into an object and return it to the front end?

The premise of the article is to use the MyBatis-Plus framework, and the following annotations are all internal to the framework.

I read a lot of tutorials on the Internet today, but I couldn't meet this requirement, and then I consulted the teacher and finally solved the problem that troubled me all day. The requirements are as follows, and the fields in the database are as follows:

Each one is of JSON type, and then I want to read this JSON type, and then return it to the front end in the form of an array. There is no JSON type in JAVA, so to receive this, either use String (returning the front end is a large string of strings, and let the front end process the rest) or use the following method to convert it into a JSON array.

1. Create a class corresponding to the properties of each object in the above array:

package io.github.talelin.latticy.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class SpecKeyValueDO {

    @JsonProperty(value = "key_id")
    private Integer keyId;

    @JsonProperty(value = "value_id")
    private Integer valueId;

    private String value;

    private String key;
}

2. Because the above is an array, use the List<> generic type to receive it. If it is a simple JSON object, you can directly use the object created above to receive it.

1. Type @TableField(typeHandler = JacksonTypeHandler.class) on the attribute

2. Add @TableName(value = "sku", autoResultMap = true) to the class for automatic mapping

package io.github.talelin.latticy.model;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import lombok.Data;

/**
 * sku
 * @author 
 */
@Data
@TableName(value = "sku", autoResultMap = true)  //一定要写好这个 autoResultMap = true
public class SkuDO extends BasePojo implements Serializable {
    private Integer id;
    
    /*省略很多属性*/

    @TableField(typeHandler = JacksonTypeHandler.class)
    private List<SpecKeyValueDO> specs;

}

3. Controller layer:

To use this kind of query, you must use the query method that comes with MyBatis-plus, that is, do not write SQL statements, because when writing SQL statements, you need to perform result mapping, so you can directly use conditional queries.

    @GetMapping("/ids/{id}") //@Positive表示必须是整数
    public List<Sku> getDetails(@PathVariable @Positive Long id) {
        return skuService.lambdaQuery().eq(Sku::getSpuId,id).list();
    }

Finally, the array will be returned:

 Otherwise it returns something like this:

Guess you like

Origin blog.csdn.net/weixin_60414376/article/details/127016009