Convert Java pojo to json String

Lilac picture Lilac · Jan 9, 2020 · Viewed 11.1k times · Source

I have the following java class

public  class TabularDescriptor extends ReportDescriptor {

    private String generatorClass;
    private String targetClass;
    private String name;
    private String sublabel;
    private String reportName;
    private List<MappingMetadata> mappings = null;
    private List<TabularColumnGroup> columnGroups = null;
    private List<TabularStates> states = null;
:
:
     and its getters and settere

I have entity classes for each of those List like MappingMetadata,TabularColumnGroup,TabularStates. I want to get a json data for this pojo classes. What can I do for it.

And what is the use of

    public JSONObject toJSON() {
        JSONObject ret = new JSONObject();
        ret.put("generatorClass", this.generatorClass);
        ret.put("targetClass", this.targetClass);
        ret.put("name", this.name);
        :
        :
        return ret;
    }

And is there anyway I can display my json content on browser if yes how can I? Thanks.

Answer

Mehrdad HosseinNejad picture Mehrdad HosseinNejad · Jan 9, 2020

You can use ObjectMapper or Gson for Class to JSON conversion and vice-versa.

(I would recommend ObjectMapper)

  • Object Mapper

Intro to the Jackson ObjectMapper

  • GSON

How to convert Java object to / from JSON

  • Comparison

Jackson(ObjectMapper) vs Gson