Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code:

import java.util.List;

public class ValueData {

    private List<ValueItems> information;

    public ValueData(){

    }

    public List<ValueItems> getInformation() {

        return information;

    }

    public void setInformation(List<ValueItems> information) {

        this.information = information;

    }

    @Override

    public String toString() {

        return String.format("{information:%s}", information);

    }

}

And the remaining code:

public class ValueItems {

    private String timestamp;

    private String feature;

    private int ean;

    private String data;


 

    public ValueItems(){

    }

    public ValueItems(String timestamp, String feature, int ean, String data){

        this.timestamp = timestamp;

        this.feature = feature;

        this.ean = ean;

        this.data = data;

    }

    public String getTimestamp() {

        return timestamp;

    }

    public void setTimestamp(String timestamp) {

        this.timestamp = timestamp;

    }

    public String getFeature() {

        return feature;

    }

    public void setFeature(String feature) {

        this.feature = feature;

    }

    public int getEan() {

        return ean;

    }

    public void setEan(int ean) {

        this.ean = ean;

    }

    public String getData() {

        return data;

    }

    public void setData(String data) {

        this.data = data;

    }

    @Override

    public String toString() {

        return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);

    }

}

Below is how I want to JSON to look like:

{

    "information": [{

        "timestamp": "xxxx",

        "feature": "xxxx",

        "ean": 1234,

        "data": "xxxx"

    }, {

        "timestamp": "yyy",

        "feature": "yyy",

        "ean": 12345,

        "data": "yyy"

    }]

}

I want to know, how to convert the Java object to JSON with Jackson in the below code: 

public static void main(String[] args) {

   // CONVERT THE JAVA OBJECT TO JSON HERE

    System.out.println(json);

}

Can anyone tell me which instance I should call and how to achieve the mentioned JSON output? 


 

1 Answer

0 votes
by (19.7k points)

Below is my code to convert the object in JSON with Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();

String json = ow.writeValueAsString(object);

Interested in Java? Check out this Java Certification by Intellipaat.     

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)

Browse Categories

...