P
P
p4p2019-07-03 15:06:53
C++ / C#
p4p, 2019-07-03 15:06:53

C# Json to List MyClass how to convert?

There is such a class with categories and types:

public class NamedListBlock
        {
            public string Category;

            public List<string> Types = new List<string>();

            public NamedListBlock(string listName, List<string> theList)
            {
                this.Category = listName;
                this.Types = theList;
            }

        }

There is json:
{ 
 "Catygocy 01": [ 
 "r1", 
 "r2", 
 "r3", 
 "r4"
 ], 
 "Catygocy 02": [ 
 "x1", 
 "x2", 
 "x3", 
 "x4"
 ], 
 "Catygocy 03": [ 
 "s1", 
 "s2", 
 "s3", 
 "s4"
 ] 
}

I'm using SimpleJSON:
var DEC = JSON.Parse("MyJson");

Categories = new List<NamedListBlock>();
List<string> types = new List<string>();

foreach (var c in DEC)
            {
                Debug.Log(c.Key);

                foreach (var t in DEC[c.Key])
                {
                    Debug.Log(t.Value);
                }

            }

here everything is well displayed in order
category 1
type
type
category 2
type type
But how do I convert this into my class?
Suppose I add categories in the
Categories.Add(new NamedListBlock("", null) { Category = n.Key, Types = ?? });
And how to dodge and add types in accordance with the categories?
foreach (var t in DEC[c.Key])
                {
                    Categories.Find(x => x.Category == c.Key).Types.Add(t.Value);
                    Debug.Log(t.Value);
                }

- that doesn't work...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Bashinsky, 2019-07-03
@p4p

static async Task Main(string[] args)
        {
            var data = "{ \r\n \"Catygocy 01\": [ \r\n \"r1\", \r\n \"r2\", \r\n \"r3\", \r\n \"r4\"\r\n ], \r\n \"Catygocy 02\": [ \r\n \"x1\", \r\n \"x2\", \r\n \"x3\", \r\n \"x4\"\r\n ], \r\n \"Catygocy 03\": [ \r\n \"s1\", \r\n \"s2\", \r\n \"s3\", \r\n \"s4\"\r\n ] \r\n}";
            var json = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(data);

            var result = json.Select(s => new NamedListBlock(s.Key, s.Value));
        }

I did it with NewtonJson, you need to convert it to SimpleJSON according to the example.
He parses it for you as a Dictionary and then you need to convert it

L
LiptonOlolo, 2019-07-03
@LiptonOlolo

In general, judging by your JSON code, you can compose a class like this:

public partial class Temperatures
{
  [JsonProperty("Catygocy 01")]
  public string[] Catygocy01 { get; set; }

  [JsonProperty("Catygocy 02")]
  public string[] Catygocy02 { get; set; }

  [JsonProperty("Catygocy 03")]
  public string[] Catygocy03 { get; set; }
}

Either provide the FULL JSON code, or try it yourself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question