Z
Z
Zimaell2020-09-29 09:26:02
C++ / C#
Zimaell, 2020-09-29 09:26:02

How to read parsed json?

I send the following string from the server

[{"id":1,"Name":"Test1"},{"id":2,"Name":"Test2"}]

accept on client

using Newtonsoft.Json;
public class StructureTest{
  public int id { get; set; }
  public string Name { get; set; }
  }
...............
  StructureTest DataTest = JsonConvert.DeserializeObject<StructureTest>(ReciveData);

  foreach( StructureTest d in DataTest ){
    Debug.Log("id =>" + d["id"]);
    Debug.Log("name =>" + d["Name"]);
    }
...............

gives me an error
error CS1579: foreach statement cannot operate on variables of type 'StructureTest' because 'StructureTest' does not contain a public instance definition for 'GetEnumerator'

I saw a solution to this problem on the net in this way
public class StructureTest : IEnumerable{
  public int id { get; set; }
  public string Name { get; set; }
  public IEnumerator GetEnumerator(){
    yield return this.id;
    yield return this.Name;
    }
  }

but then it gives me this error
error CS0021: Cannot apply indexing with [] to an expression of type 'StructureTest'

Tell me how to read correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korotenko, 2020-09-29
@Zimaell

You have an array of elements arrives.

var items = JsonConvert.DeserializeObject<StructureTest[]>(ReciveData);

  foreach( var d in items ){
    Debug.Log($"id : {d.id}");
        Debug.Log($"Name: {d.Name}");
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question