简体   繁体   中英

Single Element Nested Arrays in JSON from XML in C#

I am working with a JSON object that I am serializing from XML. All the child nodes of the XML need to be serialized as arrays. I have been trying this for a couple days now and have found nothing, but I have gotten close. The problem is that JsonConvert.SerializeObject() seems to be seeing this as a single item array, and then removing the [] array indicators in the JSON. Here is my example of what I have been doing.

The desired result is this:

{"Foo":[{"Bar":[{"This":"stuff"}]}]}

What has gotten me the closest so far is something like this...

        XElement bar = new XElement("Bar");
        bar.SetAttributeValue("This", "stuff");
        XElement[] foo = { new XElement("Foo", bar) };

But it still is not quite right. The result I get here after running JsonConvert.SerializeObject(foo) is something like this...

{"Foo":{"Bar":{"This":"stuff"}}}

For the API, each child of the parent has to be an array type, even if it only contains 1 element. The XML version of this request, which I can't use, looks like this...

 <Foo>
  <Bar This="stuff"/>
 </Foo>

I have a feeling I'm overlooking something simple, or making this more complex than it needs to be, but I could really use some help.

Thanks!

Hunts Chen in the comments had the redirect that solved my issue. Here is what the working code ended up looking like.

        XNamespace ns = "http://james.newtonking.com/projects/json";

        XElement bar = new XElement("Bar");
        userdata.SetAttributeValue(ns + "Array", true);
        userdata.SetAttributeValue("This", "stuff");
        XElement foo = new XElement("Foo", bar);
        parts.SetAttributeValue(ns+"Array", true);

        XDocument xmlbody = new XDocument();

        xmlbody.Add(foo);

        string json = JsonConvert.SerializeObject(xmlbody);

Since there is only a single element for each node, the array has to be forced. The return was exactly what I was intending.

 {"Foo":[{"Bar":[{"@This":"stuff"}]}]}}

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM