Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
        }
      ]
    }
  }
}
like image 859
Daniel Dyson Avatar asked Nov 14 '22 10:11

Daniel Dyson


1 Answers

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.

like image 147
Oleg Avatar answered Nov 16 '22 23:11

Oleg