Buvin Perera
Buvin Perera

Reputation: 491

Getting :" when converting Json object to XML in Java

Im trying to convert JsonObject to XML but it seems to be encored.

This is my JsonObject -

{
  "customerName": "cus1",
  "invoiceNumber": "in1",
  "invoiceDate": "2017-01-23",
  "amount": 110.1,
  "invoiceItems": [
    {
      "chargeName": "null",
      "subscriptionName": "TestSub",
      "amount": 129,
      "servicePeriod": "2017-01-23to 2017-02-23"
    },
    {
      "subscriptionName": "",
      "servicePeriod": "",
      "chargeDate": "",
      "chargeName": "Discounted Amount",
      "amount": -12.9
    }
  ]
}

Output I'm getting is -

{"customerName":"cus1;,"invoiceNumber":"in1;,"invoiceDate":"2017-01-23","amount":116.1,"invoiceItems":[{"chargeName":"null","subscriptionName":"TestSubd","amount":129.0,"servicePeriod":"2017-01-23to 2017-02-23"},{"subscriptionName":"","servicePeriod":"","chargeDate":"","chargeName":"Discounted Amount","amount":-12.9}]}"

Output im expecting is without encoding <customerName>cus1<customerName> format.

I have used org.json.XML to convert the json object to xml

  JsonObject invoiceDetailObj = new JsonObject();
invoiceDetailObj.addProperty("customerName", aa.get("customer").asText());

I added properties to the invoiceDetailObj so that its currently looks like the jsonObj I have added in the top

 xml = XML.toString(invoiceDetailObj);

Upvotes: 1

Views: 4219

Answers (1)

Nicolas Filotto
Nicolas Filotto

Reputation: 45005

Your problem is related to the fact that you mix com.google.gson.JsonObject from Google Gson with org.json.JSONObject. Actually, the method XML.toString(object) expects an instance of org.json.JSONObject or org.json.JSONArray or an array of org.json.JSONObject so what you get is simply the default behavior of this method when none of those types are found.

Simply rewrite your code to use org.json.JSONObject instead of com.google.gson.JsonObject, your code should then look like something like this:

JSONObject invoiceDetailObj = new JSONObject();
invoiceDetailObj.put("customerName", "cus1");
invoiceDetailObj.put("invoiceNumber", "in1");
...
String xml = XML.toString(invoiceDetailObj);

Or even better, if you have your JSON object as a String, you could simply use the constructor JSONObject(String source) to let it parse and build the JSONObject for you:

String xml = XML.toString(new JSONObject(myJSONString));

Upvotes: 3

Related Questions