Deserialize to an ICollection without the need to create an extra class

1

Hello. I am using Json.NET to deserialize my object. Today I do the following:

JsonConvert.DeserializeObject<ICollection<TModelo>>(stream.ReadToEnd());

Currently I have to create an extra class ( Produtos ) because the return is an array. Within Class Produtos so I have:

[JsonProperty("products")]
public ICollection<Produto> ListaProdutos { get; set; }

That way I'm getting deserialized. My question is: Is there any other way I can do this if I always need the Produtos class? That is, to make this conversion "automatic" without the need for an additional class?

I mention this because I have several classes (this is an API) and I would like a more elegant way of doing this.

Thank you

    
asked by anonymous 26.12.2017 / 19:11

1 answer

0

You can use Newtonsoft that is already being used in the dynamic mode mode, it uses LINQ:

 json = @"{name: 'Leonardo', lastname: 'Bonetti'}";
 JObject jObject = (JObject)JsonConvert.DeserializeObject(json);
 Debug.WriteLine((String)jObject["name"]); //Leonardo

If you only have a Array for example you can also Deserialize directly:

string json = @"['Small', 'Medium','Large']";
JArray a = JArray.Parse(json);
Debug.WriteLine((int)a.Count);//3

You can also read directly from a file through StreamReader:

using (StreamReader reader = File.OpenText(@"c:\meuJson.json"))
{
    JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
}

Source and other example: link

Or you can use the same top-down approach with the dynamic (it is a type of variable that ignores type checking in compilation, this process happens during execution ie it is dynamic, but it has the negative side because some methods do not accept dynamic types) that is a little more readable: / p>

Object access example:

string json = @"{name: 'Leonardo', lastname: 'Bonetti'}";
dynamic obj = JObject.Parse(json);
String name = obj.name; //Leonardo

Example of access to a direct variable:

 string json = @"['Small', 'Medium','Large']";
 dynamic obj = JArray.Parse(json);
 int name = obj.Count; //Leonardo

Access example reading directly from StreamReader:

using (StreamReader reader = File.OpenText(@"c:\meuJson.json"))
{
    dynamic obj = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
}

Source of% use%: link

    
26.12.2017 / 19:39