Daniel Dyson
Daniel Dyson

Reputation: 13230

xml data lost in JSON conversion

I am getting the following result from converting xml to JSON, using more than one conversion library. As you can see, the property name attributes are lost, as are the Item name attributes. Why?

Does anyone have recommendations on how I might change my XML to make it more conversion friendly?

<Asset name="xyz">
  <Property name="p1">Value 1</Property> 
  <Property name="p2">Value 2</Property> 
  <TimeSeries name="TimeSeries Name 1">
    <Item name="30 Apr 2009">97.47219</Item> 
    <Item name="01 May 2009">97.16496</Item> 
    <Item name="05 May 2009">97.34606</Item> 
  </TimeSeries>
</Asset>

Returns:

{
  "Asset": {
    "@attributes": {
      "name": "xyz"
    },
    "Property": ["Value 1", "Value 2"],
    "TimeSeries": {
      "@attributes": {
        "name": "TimeSeries Name 1"
      },
      "Item": ["97.47219", "97.16496", "97.34606"]
    }
  }
}

I have tried the following, but both the XML and JSON are a lot more verbose:

<Asset name="xyz">
  <Property><name>p1</name><value>Value 1</value></Property> 
  <Property><name>p2</name><value>Value 2</value></Property> 
  <TimeSeries name="TimeSeries Name 1">
      <Item><date>30 Apr 2009</date><value>97.47219</value></Item> 
      <Item><date>01 May 2009</date><value>97.16496</value></Item> 
      <Item><date>05 May 2009</date><value>97.34606</value></Item> 
  </TimeSeries>
</Asset>

resulting in...

{
  "Asset": {
    "@attributes": {
      "name": "xyz"
    },
    "Property": [{
      "name": "p1",
      "value": "Value 1"
    }, {
      "name": "p2",
      "value": "Value 2"
    }],
    "TimeSeries": {
      "@attributes": {
        "name": "TimeSeries Name 1"
      },
      "Item": [{
          "date": "30 Apr 2009",
          "value": "97.47219"
        },
        {
          "date": "01 May 2009",
          "value": "97.16496"
        }, {
          "date": "05 May 2009",
          "value": "97.34606"
        }
      ]
    }
  }
}

Upvotes: 5

Views: 536

Answers (1)

Oleg
Oleg

Reputation: 221997

Probably you should never use attributes in the source XML file if you use this conversion tool.

You main problem I see is that you don't design the data yourself and try usage of a strange tool. If you use ASP.NET on the server side, it is much better to design your C# classes, initialize an instance of the classes with any test data and use JSON serialization like DataContractJsonSerializer or use a simple Web Service. Look at Can I return JSON from an .asmx Web Service if the ContentType is not JSON? or How do I build a JSON object to send to an AJAX WebService? as examples.

Upvotes: 1

Related Questions