Removing JSON deserialization with variable names / values ​​in an object in C #

I am using C # .NET 4.0 to parse JSON into a custom object. I am using JavaScriptSerializer.Deserialize to map it to the class I wrote. The problem is that the JSON name / value pairs are not static and vary depending on the isChain argument, as can be seen from this JSON snippet (best link below):

{ "STATE_WALK_LEFT":{ "isChain":"1", "x":"1" }, "STATE_WALK_LEFT_0":{ "x":"0" }, "STATE_WALK_LEFT_1":{ "x":"40" }, "STATE_WALK_LEFT_2":{ "x":"80" }, "STATE_WALK_RIGHT":{ "isChain":"0" }, "STATE_RUN_LEFT":{ "isChain":"0" } } 

Chains can have from _STATE_0 to _STATE_25 records in chains. Is there a way to save this data, so I don't need to write 12 * 26 empty classes:

 public StateWalkLeft0 STATE_WALK_LEFT { get; set; } public StateWalkLeft0 STATE_WALK_LEFT_0 { get; set; } public StateWalkLeft1 STATE_WALK_LEFT_1 { get; set; } public StateWalkLeft2 STATE_WALK_LEFT_2 { get; set; } public StateWalkLeft3 STATE_WALK_LEFT_3 { get; set; } 

Is there a library or some other way that I could use to partially analyze only the fields STATE_0, STATE_1, etc.? Could you suggest a way to add these newly added JSON pairs?

Edited for clarification : To get an idea of ​​what I'm working with, here is a class derived from JSON:

Check out my full class to see what JSON contains

Basically, I just need a way to store these recently implemented chains in this class somehow for processing. All these classes / properties are generated from these JSON.

+6
source share
1 answer

Use Newtonsoft Json.NET and as an example of the following code

 internal struct ChainX { public int x { get; set; } public int isChain { get; set; } } static string json = @"{ ""STATE_WALK_LEFT"":{ ""isChain"":""1"", ""x"":""1"" }, ""STATE_WALK_LEFT_0"":{ ""x"":""0"" }, ""STATE_WALK_LEFT_1"":{ ""x"":""40"" }, ""STATE_WALK_LEFT_2"":{ ""x"":""80"" }, ""STATE_WALK_RIGHT"":{ ""isChain"":""0"" }, ""STATE_RUN_LEFT"":{ ""isChain"":""0"" } }"; 

and a line of code for dictionary deserialization:

 var values = JsonConvert.DeserializeObject<Dictionary<string, ChainX>>(json); 

after that you can get simple access values ​​using the dictionary key:

 ChainX valueWalkLeft1 = values["STATE_WALK_LEFT_1"]; 
+2
source

Source: https://habr.com/ru/post/915520/


All Articles