如何反序列化我的JSON?

时间:2016-02-06 17:50:20

标签: c# restsharp

下一步要采取什么措施?我希望能够编写id值为ex 1的块。或者带有GPIO值为3的块,其中的内容很简单,可能是WriteLine(id1)
Relay.cs

public class Relay
{
    public int GPIO { get; set; }
    public int id { get; set; }
    public int status { get; set; }
    public string type { get; set; }
}

Program.cs的

static void Main(string[] args)
    {
        var client = new RestClient("http://192.168.0.3:1337/auto/api/v1.0/");
        var request = new RestRequest("relays", Method.GET);  
        request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

        var response = client.Execute<Relay>(request);

        Console.WriteLine(response.Content);
        Console.ReadLine();
    }

和我的数组在192.168.0.3:1337/auto/api/v1.0/relays

{
 "relays": [
  {
   "GPIO": 2, 
   "id": 1, 
   "status": 0, 
   "type": "Relay"
  }, 
  {
   "GPIO": 3, 
   "id": 2, 
   "status": 0, 
   "type": "Relay"
  }
 ]
}

对不起,如果有什么不清楚,或答案很简单,我很抱歉。如果我错过了重要内容,请指出并发布它!

3 个答案:

答案 0 :(得分:0)

您需要将JSON解析为对象来操作它们,而且您的REST客户端似乎已经完成了它,只需要传递正确的类型。

1 - 创建类结构,如您收到的结构:

    public class Relay
    {
        public int GPIO { get; set; }
        public int id { get; set; }
        public int status { get; set; }
        public string type { get; set; }
    }

    public class RelayCollection
    {

        public Relay[] relays { get; set; }

    }

2 - 解析收到的json:

var relayCollection = client.Execute<RelayCollection>(request);

现在你有了relayCollection.relays中的所有中继,操纵它们就像任何其他数组/类一样

答案 1 :(得分:0)

您可以在Relay列表中对其进行反序列化,并迭代并读取您想要的任何值

static void Main(string[] args)
    {
        var client = new RestClient("http://192.168.0.3:1337/auto/api/v1.0/");
        var request = new RestRequest("relays", Method.GET);  
        request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

        var response = client.Execute<Relay>(request);
        JavaScriptSerializer ser = new JavaScriptSerializer();
          var relayList = ser.Deserialize<List<Relay>>(response.Content);
         foreach(Relay relay in relayList) 
        Console.WriteLine(relay.ID);
        Console.ReadLine();
    }

答案 2 :(得分:0)

事先我为我的英语道歉,但您可以通过创建类的列表来序列化json,然后像这样反序列化json:

public class Relay {
int GPIO;
public int gPIO {get {return GPIO;} set {GPIO=value;}}
int Id;
public int ID {get {return Id;} set {Id = value;}}
int Status;
public int status {get {return Status;} set {Status = value;}}
string Type;
public string  type {get {return Type;} set {Type = value;}}
}

现在创建一个班级列表

List<Relay > relayList = new List<Relay >();

最后deserealize json

relayList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Relay>>(request);