获取:“在Java中将Json对象转换为XML时

时间:2017-01-25 08:53:04

标签: java json xml

我试图将JsonObject转换为XML,但它似乎已被加入。

这是我的JsonObject -

2016-01-25  17:30:13

我得到的输出是 -

{
  "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
    }
  ]
}

我期待的输出没有编码{"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}]}" 格式。

我使用<customerName>cus1<customerName>将json对象转换为xml

org.json.XML

我在invoiceDetailObj中添加了属性,以便它当前看起来像我在顶部添加的jsonObj

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

1 个答案:

答案 0 :(得分:2)

您的问题与com.google.gson.JsonObjectorg.json.JSONObject XML.toString(object)混合的事实有关。实际上,方法org.json.JSONObject需要org.json.JSONArrayorg.json.JSONObject的实例或org.json.JSONObject的数组,所以你得到的只是这种方法的默认行为,而这些类型都不是找到了。

只需重写代码即可使用com.google.gson.JsonObject代替JSONObject invoiceDetailObj = new JSONObject(); invoiceDetailObj.put("customerName", "cus1"); invoiceDetailObj.put("invoiceNumber", "in1"); ... String xml = XML.toString(invoiceDetailObj); ,您的代码应如下所示:

JSON

或者甚至更好,如果您将String对象作为JSONObject(String source),则可以使用构造函数JSONObject让它为您解析并构建String xml = XML.toString(new JSONObject(myJSONString));

function disabledDate(date) {
            //get all dates from Server in Array
            var disabledDates = []; // add all dates with (,) separated here.
           for(i=0; i <disabledDates.length;i++)
            {
                // Parse the date one by one and match with 
            if( date.getDate() == PARSED_DATE)
            return true;                    
            }
          return false;


        };