Json看起来像:
[{"id":"001788fffe2e6479","internalipaddress":"192.168.1.2"}]
我的反序列化C#代码(使用Newtonsoft):
public class ipBridge
{
public string Id { get; set; }
public string InternalIpAddress { get; set; }
public string MacAddress { get; set; }
}
public class LocatedBridge
{
public string BridgeId { get; set; }
public string IpAddress { get; set; }
}
和:
var request = (HttpWebRequest)WebRequest.Create("https://www.test.com/api");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
ipBridge[] responseModel = JsonConvert.DeserializeObject<ipBridge[]>(responseString); //responseString = [{"id":"001788fffe2e6479","internalipaddress":"192.168.1.2"}]
responseModel.Select(x => new LocatedBridge() { BridgeId = x.Id, IpAddress = x.InternalIpAddress }).ToList();
Console.WriteLine($"{ip}"); // ip = internalipaddress of JSON, HOW?
答案 0 :(得分:1)
您有有效的反序列化代码,而问题实际上与它无关。您要访问的是反序列化的对象字段。
ipBridge[] responseModel = JsonConvert.DeserializeObject<ipBridge[]>(responseString);
var locatedBridgeModel = responseModel.Select(x => new LocatedBridge() { BridgeId = x.Id, IpAddress = x.InternalIpAddress }).ToList();
Console.WriteLine($"{responseModel[0].InternalIpAddress}");
//or
Console.WriteLine($"{locatedBridgeModel[0].IpAddress}");
//or
Console.WriteLine($"{locatedBridgeModel.First().IpAddress}");
答案 1 :(得分:0)
从ipBridge
,[
(方括号)的出现看来,您的JSON中有]
个对象(基于JSON中使用的名称),我可以告诉它是这些对象的列表。因此,应将其反序列化为List<ipBridge>
。
使用此代码:
var json = @"[{ ""id"":""001788fffe2e6479"",""internalipaddress"":""192.168.1.2""}]";
var deserialized = JsonConvert.DeserializeObject<List<ipBridge>>(json);