Deserialize for an Icollection without the need to create an extra class

Asked

Viewed 45 times

1

Hello. I am using Json.NET to deserialize my object. Today I do it as follows:

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

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

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

That way I’m able to deserialize. My question is: Is there another way I can do this I always need the class Produtos? That is, make this conversion "automatic" without the need for an additional class?

I say this because I have several classes (it is an API) and I would like a more elegant way to work this.

Thank you

1 answer

0

You can use your own Newtonsoft which is already being used has this dynamic mode mode, it uses LINQ:

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

In case you only have one Array for example it is also possible to 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: https://www.newtonsoft.com/json/help/html/LINQtoJSON.htm

Or you can use the same top approach next to the resource Dynamic(is a type of variable that ignores type checking in the compilation, this process happens during the execution, that is, it is dynamic, but has the negative side because some methods do not accept dynamic types) that is a little more readable:

Example of object access:

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

Example of reading access directly from Streamreader:

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

Source of use of dynamic: https://stackoverflow.com/questions/4535840/deserialize-json-object-into-dynamic-object-using-json-net

  • That way I can’t hold the line [JsonProperty("products")] that is necessary so that when deserialize the application knows that the array has this name (products).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.