简体   繁体   English

将字符串数据从mysql表转换为java中的json列表

[英]Convert String data from mysql table to json list in java

I want to convert a string to json list. 我想将字符串转换为json列表。 I am currently working on a web api using spring boot. 我目前正在使用spring boot处理web api。 There is a table which contains multiple value at a ssingle column and similarly all the columns are having multi values. 有一个表在ssingle列包含多个值,类似地,所有列都具有多个值。 Like: There is a car company. 喜欢:有一家汽车公司。 There is a column named models - which contains more than one models and then there there is a price column which contains all the models price respectively. 有一个名为models的列 - 它包含多个模型,然后有一个价格列,分别包含所有模型的价格。 Now I have to convert those strings to json format. 现在我必须将这些字符串转换为json格式。

I tried using the split() in java for that but that is giving the address location as output. 我尝试在java中使用split() ,但这是将地址位置作为输出。

Model class 模型类

..........//getters and setters and declarations

    @Override
    public String toString() {

        String ar = car_type;
        String ar1[]=ar.split(",");
        int l = ar1.length;
        return "{" +
                "\"car_comp\":" +"\"" + car_comp+ "\""+"," +
                "\"car_type\":" +"\""+ ar1 + "\""+","+
                "\"car_price\":" +"\""+ car_price+ "\""+","+
                "\"car_comp_value\":"+"\"" + car_comp_value +"\""+
                '}';
    }

I used the length function to check whether the array is being created of the right size or not. 我使用length函数来检查是否正在创建大小合适的数组。

The Output 输出

 "car_comp": {
        "car_comp": "bmw",
        "car_type": "[Ljava.lang.String;@4017b770",
        "car_price": "$1500",
        "car_comp_value": "$65.4M"
    }

PLEASE IGNORE THE DATA.. But the car type is showing not what I expected. 请忽略数据......但是车型并没有显示出我的预期。 To be honest this is my first time working in web api and json and I don't have much idea how to do things with it. 说实话,这是我第一次在web api和json工作,我不知道如何用它做事。 The Expected Output : 预期产出:

 "car_comp": {
        "car_comp": "bmw",
        "car_type": [{modelA},{modelB},{modelC}],
        "hb_unit_hints": "Kg",
        "hb_value": "65.4"
    }

Thanks in Advance. 提前致谢。

Since you are using spring boot, You could implement that using ObjectMapper . 由于您使用的是Spring引导,因此您可以使用ObjectMapper实现它。

So I will just create model for clear explanation 因此,我将创建模型以进行清晰的解释

Car Model 汽车模型

class Car {
    @JsonProperty(value = "car_company")
    private String carCompany;
    @JsonProperty(value = "car_type")
    private List<CarType> carType;
    @JsonProperty(value = "car_price")
    private String carPrice;

   // Getter, Setter, All Args
}

Car Type 车型

class CarType {
    @JsonProperty(value = "type")
    private String type;

    //Getter, Setter, All Args
}

Implementation 履行

ObjectMapper mapper = new ObjectMapper();
List<CarType> carTypes = Arrays.asList(new CarType("SEDAN"), new CarType("HATCHBACK"));
Car car = new Car("Telsa", carTypes, "1000");
System.out.println(mapper.writeValueAsString(car));  

//Output : 
//{"car_company":"Telsa","car_type":[{"type":"SEDAN"},{"type":"HATCHBACK"}],"car_proce":"1000"}


JsonNode jsonNode = mapper.valueToTree(car);

// It also gives you JsonNode

String ar = car_type; String ar = car_type;

String ar1[]=ar.split(","); String ar1 [] = ar.split(“,”);

There, I feel your problem is trying to map a String column of a table entity to a List model field. 在那里,我觉得你的问题是试图将表实体的String列映射到List model字段。 If you had a car model with List field then model to JSON string conversion is straight-forward using jackson-objectmapper like: 如果你有一个带有List字段的汽车模型,那么使用jackson-objectmapper模型到JSON字符串转换是直截了当的:

Car model: 汽车模型:

public class Car {
    String car_comp;
    List<String> car_type;
    String car_price;
    String car_comp_value;
}

Converting Car model object to JSON string: 将Car model对象转换为JSON字符串:

ObjectMapper objectMapper = new ObjectMapper();

Car car = new Car();
car.car_comp = "BMW";
car.car_type = Arrays.asList("modelA", "modelB", "modelC");
car.car_price = "$1500";
car.car_comp_value = "$65.4M";

String json = objectMapper.writeValueAsString(car);

If you are using JPA Entity to map database tables to models, you can use javax.persistence.AttributeConverter to convert a comma-separated String column to a List field of the entity, like: 如果使用JPA Entity将数据库表映射到模型,则可以使用javax.persistence.AttributeConverter将逗号分隔的String列转换为实体的List字段,如:

Custom attribute converter: 定制属性转换器:

public class CarTypeConverter implements AttributeConverter<List<String>, String> {
    @Override
    public Long convertToDatabaseColumn(List<String> attribute) {
        if (attribute == null) return null;
        return attribute.stream().reduce((x, y) -> x + "," + y).orElse("");
    }

    @Override
    public List<String> convertToEntityAttribute(String dbColumnValue) {
        if (dbColumnValue == null) return null;
        String[] typeArray = dbColumnValue.split(",");
        List<String> typeList = Arrays.stream(typesArray).collect(Collectors.toList());
        return typeList;
    }
}

Car database entity: 汽车数据库实体:

@Entity
@Table(name = "car_comp")
class Car {
    @Column(name = "car_comp")
    String car_comp;

    @Column(name = "car_type")
    @Convert(converter = CarTypeConverter.class)
    List<String> car_type;

    @Column(name = "car_price")
    String car_price;

    @Column(name = "car_value")
    String car_comp_value;
    //getters and setter below...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM