Search code examples
javajsonjacksonjackson2

Jackson JSONGenerator adds newline,backlash etc and does not display the given content in formatted order


I am using the Jackson to convert a List of XML to JSON after converting each event from the XML List<> I am storing the converted JSON into List<String>.

After all conversion, I have to create a new JSON with some outer elements and then finally add the converted JSON from previously-stored List<String>. Everything works fine but when I add the JSON from List<String> it also adds the \n, \ and all my formatting goes away. I am not sure why it does like this.

I tried to search and use the various methods mentioned but nothing seems to work so thought of posting here the same. Really sorry if found a duplicate.

Following is the code: (Please note: This is a sample direct code I have provided so that anyone who is trying can try directly to figure out the issue. However, another sample code with a complete workflow has been given below. Just to provide an indication how I am doing actually in my application. However, both are adding the \ and removing the formatting.)

I just want to know how to avoid adding these \ and other non-relevant characters to my Final JSON and add formatting to it.

public class Main {
    public static void main(String[] args) throws IOException {
        List<String> stringEvents = new ArrayList<>();
        stringEvents.add("{\n" +
                "  isA : \"Customer\",\n" +
                "  name : \"Rise Against\",\n" +
                "  age : \"2000\",\n" +
                "  google:sub : \"MyValue\",\n" +
                "  google:sub : \"MyValue\"\n" +
                "}");

        JsonFactory factory = new JsonFactory();
        StringWriter jsonObjectWriter = new StringWriter();
        JsonGenerator generator = factory.createGenerator(jsonObjectWriter);
        generator.writeStartObject();
        generator.writeStringField("schema", "1.0");
        generator.writeFieldName("eventList");
        generator.writeStartArray();
        stringEvents.forEach(event->{
            try {
                generator.writeObject(event);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        generator.writeEndArray();
        generator.writeEndObject();
        generator.close();
        System.out.println(jsonObjectWriter.toString());
    }
}

Following is the output I am getting:

{"isA":"Customer","name":"Rise Against","age":"2000"}
{"schema":"1.0","eventList":["{\"isA\":\"Customer\",\"name\":\"Rise Against\",\"age\":\"2000\"}","{\"isA\":\"Customer\",\"name\":\"Rise Against\",\"age\":\"2000\"}"]}

Following is my complete workflow and code:

  1. I am reading the XML file and performing the unmarshalling of the XML to Customer.class.
  2. I am performing the JSON Conversion and storing the converted JSON into List<String>.
  3. After all conversion I am creating my Final JSON with all header information.

Following is my Customer.class:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, visible = true, property = "isA")
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@XmlRootElement(name = "extension")
@XmlType(name = "extension", propOrder = {"name", "age"})
@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
@AllArgsConstructor
@ToString
@NoArgsConstructor
public class Customer {
    @XmlTransient
    private String isA;

    @XmlPath("customer/name/text()")
    private String name;

    @XmlPath("customer/age/text()")
    private String age;
}

Following is my Unmarshaling and Json Creation class:

public class Unmarshalling {

    public static void main(String[] args) throws JAXBException, XMLStreamException, FactoryConfigurationError, IOException {
        final InputStream inputStream = Unmarshalling.class.getClassLoader().getResourceAsStream("customer.xml");
        final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        final Unmarshaller unmarshaller = JAXBContext.newInstance(Customer.class).createUnmarshaller();
        final Customer customer = unmarshaller.unmarshal(xmlStreamReader, Customer.class).getValue();
        final String jsonEvent = new ObjectMapper().writeValueAsString(customer);
        System.out.println(jsonEvent);
        List<String> stringEvents = new ArrayList<>();
        stringEvents.add(jsonEvent);
        stringEvents.add(jsonEvent);

        JsonFactory factory = new JsonFactory();
        StringWriter jsonObjectWriter = new StringWriter();
        JsonGenerator generator = factory.createGenerator(jsonObjectWriter);
        generator.writeStartObject();
        generator.writeStringField("schema", "1.0");
        generator.writeFieldName("eventList");
        generator.writeStartArray();
        stringEvents.forEach(event->{
            try {
                generator.writeObject(event);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        generator.writeEndArray();
        generator.writeEndObject();
        generator.close();
        System.out.println(jsonObjectWriter.toString());

    }
}

Following is my xml file:

<extension xmlns:google="https://google.com">
    <customer>
        <name>Rise Against</name>
        <age>2000</age>
    </customer>
</extension>


Solution

  • After trying for few more things I tried generator.writeRaw(event); and that worked.

    import com.fasterxml.jackson.core.JsonFactory;
    import com.fasterxml.jackson.core.JsonGenerator;
    
    import java.io.IOException;
    import java.io.StringWriter;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Main {
        public static void main(String[] args) throws IOException {
            List<String> stringEvents = new ArrayList<>();
            stringEvents.add("{\n" +
                    "  isA : \"Customer\",\n" +
                    "  name : \"Rise Against\",\n" +
                    "  age : \"2000\",\n" +
                    "  google:sub : \"MyValue\",\n" +
                    "  google:sub : \"MyValue\"\n" +
                    "}");
    
            JsonFactory factory = new JsonFactory();
            StringWriter jsonObjectWriter = new StringWriter();
            JsonGenerator generator = factory.createGenerator(jsonObjectWriter);
            generator.writeStartObject();
            generator.writeStringField("schema", "1.0");
            generator.writeFieldName("eventList");
            generator.writeStartArray();
            stringEvents.forEach(event->{
                try {
                    generator.writeRaw(event);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            generator.writeEndArray();
            generator.writeEndObject();
            generator.close();
            System.out.println(jsonObjectWriter.toString());
        }
    }