The_Fox
The_Fox

Reputation: 99

JsonConvert.DeserializeObject isn't working in my .NET Core web app

Currently, I'm developing a .NET Core app with version 2.2. I get a XML response from a Web API which I cannot change. I looks like this:

<?xml version="1.0" encoding="UTF-8"?><GetInformation>
<d1>PL11VTMICE</d1>
<d2>PL-BL02912</d2>
<d3>BL</d3>
<d4>0</d4>
<d5>MTR</d5>
<d6>405</d6>
<d7/>
<d8/>
<d9/>
<d10>2019-10-15 13:29:07.000</d10>

I have a model class which looks like this:

public class Data
{
    [Required]
    public string d1 { get; set; }
    public string d2 { get; set; }
    public string d3 { get; set; }
    public string d4 { get; set; }
    public string d5 { get; set; }
    public string d6 { get; set; }
    public string d7 { get; set; }
    public string d8 { get; set; }
    public string d9 { get; set; }
    public string d10 { get; set; }
}
public class Informations
{
    public List<Data> GetInformation { get; set; }
}

The conversion from XML to JSON works fine with this:

XmlDocument doc = new XmlDocument();
var res = await client.GetAsync("some_address");
            if (res.IsSuccessStatusCode)
            {
                var result = res.Content.ReadAsStringAsync().Result;
                doc.LoadXml(result);

                string jsontest = JsonConvert.SerializeXmlNode(doc);
            }

When I look at my "jsontest" variable at runtime it looks like this: Visual Studio tester

And when I try to deserialize it to an object:

Informations bob = JsonConvert.DeserializeObject<Informations>(jsontest);

I get the following error:

  • ex {Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[xxx.xxx.Data]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

I already tried many solutions from the web e.g. with the JsonProperty Tag from here: JSON Property but unfortunately without any difference. Hopefully, you can help me.

Thanks in advance.

Upvotes: 0

Views: 1484

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129697

The problem is that GetInformation is not a list in your JSON; it is a single object.

To fix, change this line in your Informations class:

public List<Data> GetInformation { get; set; }

to this:

public Data GetInformation { get; set; }

Fiddle: https://dotnetfiddle.net/wUPNfq

Upvotes: 1

Related Questions