Ask a questionAsk a question
 

QuestionJSON array vs single element deserilization

  • Thursday, November 05, 2009 4:59 PMGeorge Ciubotaru Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Has Code
    Hello,

    I'm using one object in which I want de deserialize data from multiple formats (for the moment just 2: XML and JSON). Here is how the object will look like: 
        [DataContract]
        [XmlRoot(ElementName = "root")]
        public class Person
        {
            [DataMember(Name="name")]
            [XmlElement("name")]
            public string Name { get; set; }
    
            [DataMember(Name = "account")]
            [XmlElement("account")]
            public List<Account> Accounts { get; set; }
        }
    
        [DataContract]
        public class Account
        {
            [DataMember(Name = "id")]
            [XmlAttribute("id")]
            public string Id { get; set; }
        }
    
    

    The input XML could be: 

    <root>
      <name>John</name>
      <account id="1"/>
      <account id="2"/>
      <account id="3"/>
    </root>
    

    And the JSON input could be:

    {
      "name":"John",
      "account":  [
        { "id": "1" },
        { "id": "2" },
        { "id": "3" },
      ]
    }

    This works fine untill I'm getting as input a file with just one 'account' element. For JSON the "account" element isn't an array anymore but just a simple element (so the "List<Account> Accounts" type doesn't apply, it only works with "Account Accounts"):

    {
      "name":"John",
      "account": { "id": "1" }
    }

    For JSON I'm using DataContractJsonSerializer for deserialization.

    Is there any way to have just one single object and deserialize both JSONs in it (there is no way of modifying the input JSONs, this is how they are generated)?

    Thanks,
    George
     

    • Moved byeryangMSFTFriday, November 13, 2009 10:04 AM (From:.NET Base Class Library)
    •  

All Replies

  • Friday, November 13, 2009 10:04 AMeryangMSFTUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Hi,
    Thanks for your post, but it is tend to get quicker and better response/support in http://forums.asp.net where asp experts live in, you can consider posting your question there, good luck:)

    Thanks,
    Eric
    Please remember to mark helpful replies as answers and unmark them if they provide no help.