0

I want to convert a string to json list. I am currently working on a web api using spring boot. There is a table which contains multiple value at a ssingle column and similarly all the columns are having multi values. 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. Now I have to convert those strings to json format.

I tried using the split() in java for that but that is giving the address location as output.

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.

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. The Expected Output :

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

Thanks in Advance.

Sayanto Roy
  • 119
  • 1
  • 13
  • There is no inherent way of printing an array as-is. You will have to convert into ArrayList or traverse over the array and print. – CS_noob Jun 17 '19 at 08:27
  • Possible duplicate of [How to convert jsonString to JSONObject in Java](https://stackoverflow.com/questions/5245840/how-to-convert-jsonstring-to-jsonobject-in-java), you just have to convert your array into a string and follow this question. – Austin Schaefer Jun 17 '19 at 08:27
  • There are existing libraries for such things. Use one! https://github.com/FasterXML/jackson or https://github.com/google/gson – Alan Hay Jun 17 '19 at 08:28
  • Spring Data Web already includes Jackson. Add annotations on the Car Component class and use it to convert your object into JSON – Aditya Jun 17 '19 at 08:59

2 Answers2

0

Since you are using spring boot, You could implement that using 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
Avi
  • 1,458
  • 9
  • 14
0

String ar = car_type;

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. If you had a car model with List field then model to JSON string conversion is straight-forward using jackson-objectmapper like:

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:

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:

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...
}
Community
  • 1
  • 1
lprakashv
  • 1,121
  • 10
  • 19
  • List cannot be converted to List . In the custom attribute class convertToEntityAttributes() . I tried to change the Role to String but that is not giving the required output. – Sayanto Roy Jun 17 '19 at 14:02
  • Sorry my bad, it was a typo. Fixed it. It is List instead of List – lprakashv Jun 17 '19 at 14:53