将XML转换为JSON时,C#强制整数

时间:2016-11-10 10:47:49

标签: c# json xml

我正在尝试将XML转换为JSON,以便为API生成HTTP POST请求。我收到一个错误,因为其中一个字段是整数而不是字符串。从我读过的内容中添加" json:Integer =" true""到节点将导致它成为一个int,但这似乎并没有为我工作。这是xml和生成的json。数组正在工作,但整数不是。

<shipments json:Array="true" xmlns:json="http://james.newtonking.com/projects/json">
    <shipment_tracking_number />
    <response_shipment_date>2016-10-18T01:00:00.0000000-04:00</response_shipment_date>
    <response_shipment_method>UPS Ground</response_shipment_method>
    <expected_delivery_date>2016-10-18T01:00:00.0000000-04:00</expected_delivery_date>
    <ship_from_zip_code>12345</ship_from_zip_code>
    <carrier_pick_up_date>2016-10-18T01:00:00.0000000-04:00</carrier_pick_up_date>
    <carrier>UPS</carrier>
    <shipment_items json:Array="true">
        <shipment_item_id>FF12345K</shipment_item_id>
        <alt_shipment_item_id>1234567890</alt_shipment_item_id>
        <merchant_sku>B00xxxx</merchant_sku>
        <response_shipment_sku_quantity json:Integer="true">1</response_shipment_sku_quantity>
    </shipment_items>
</shipments>
  

string jsonrequest = JsonConvert.SerializeXmlNode(doc,   Newtonsoft.Json.Formatting.None,true);

{"shipments":[
    {
        "shipment_tracking_number":null,
        "response_shipment_date":"2016-10-18T01:00:00.0000000-04:00",
        "response_shipment_method":"UPS Ground",
        "expected_delivery_date":"2016-10-18T01:00:00.0000000-04:00",
        "ship_from_zip_code":"12345",
        "carrier_pick_up_date":"2016-10-18T01:00:00.0000000-04:00",
        "carrier":"UPS",
        "shipment_items":[
        {
            "shipment_item_id":"FF12345K",
            "alt_shipment_item_id":"1234567890",
            "merchant_sku":"B00xxxx",
            "response_shipment_sku_quantity":"1"
        }]
    }]
}

我需要"response_shipment_sku_quantity":"1"显示为"response_shipment_sku_quantity":1,但它似乎无法正常工作。我可以修改XML或执行转换的代码。只要能做到这一点,我不介意哪个。

1 个答案:

答案 0 :(得分:1)

您错误地定义了属性。这就是它的样子。

<response_shipment_sku_quantity json:Type='Integer'>1</response_shipment_sku_quantity>

修改

Newtonsoft.Json XmlNodeConverter

查看方法private void SerializeNodestring dataType = GetDataType(node);他们建议使用此定义。

另一个选项是Deserialize xmlclass,其中包含适当的属性类型,之后SerializeJson