Shubham Jain
Shubham Jain

Reputation: 17553

How to convert JSON object into java jsonReader

I have a JSON as below:-

{
    "products":
    {
        "productsApp15": {
            "code": "productsApp16",
            "name": "productsApp16",
            "attribute_set": "Apparel",
            "product_type": "product",
            "status": "active"
            }
    }
}

Now I need a function which can convert it like below automatically:-

 final JsonReader jsonReader = Json.createReader(new StringReader("{\n" +
                "    \"products\":\n" +
                "    {\n" +
                "        \"productsApp13\": {\n" +
                "            \"code\": \"productsApp13\",\n" +
                "            \"name\": \"productsApp13\",\n" +
                "            \"attribute_set\": \"Apparel\",\n" +
                "            \"product_type\": \"product\",\n" +
                "            \"status\": \"active\"\n" +
                "            }\n" +
                "    }\n" +
                "}"));

For that I tried to append/concatenate the string with /n but it was taken up as new line. I know it is right to but is there any way by which I can get that output automatically.

I tried something like below:-

        String sCurrentLine;
        StringBuilder sb = new StringBuilder("");
        br = new BufferedReader(new FileReader("./src/test/com/testdata/HTTPHelperTest.csv"));

    while ((sCurrentLine = br.readLine()) != null) {
        sb.append(sCurrentLine);
        sb.append("\n");
    }
    br.close();
    System.out.println("Value Json"+sb);

Any solution is appreicable.

Upvotes: 0

Views: 343

Answers (1)

Harshul Pandav
Harshul Pandav

Reputation: 1036

You need to add an escape character \ for \n

 while ((sCurrentLine = br.readLine()) != null) {
        sb.append(sCurrentLine);
        sb.append("\\n");
    }

Upvotes: 1

Related Questions