Dan Hastings
Dan Hastings

Reputation: 3280

C# force integer when converting XML to JSON

I am attempting to convert XML into JSON in order to generate a HTTP POST request to an API. I am getting an error because one of the fields is meant to be an integer instead of a string. From what i have read adding "json:Integer="true"" to the node will cause it to become an int, but this doesnt seem to be working for me. Here is the xml and the resulting json. The arrays are working, but the integer is not.

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

I need "response_shipment_sku_quantity":"1" to show up as "response_shipment_sku_quantity":1, but it doesnt seem to be working. I can modify the XML or the code that performs the conversion. I dont mind which as long as this can be done.

Upvotes: 2

Views: 2524

Answers (1)

mybirthname
mybirthname

Reputation: 18127

You define the attribute wrongly. This is how it should look like.

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

EDIT:

Newtonsoft.Json XmlNodeConverter

Look methods private void SerializeNode and string dataType = GetDataType(node); they suggest this definition.

Another option is to Deserialize the xml to class with proper types for the properties and after that Serialize it to Json.

Upvotes: 1

Related Questions