jck91
jck91

Reputation: 11

Deserialize JSON - How can I deserialize this JSON?

Json looks like:

 [{"id":"001788fffe2e6479","internalipaddress":"192.168.1.2"}]

My C# code for deserialize (using 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; }
    }

and:

        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?

Upvotes: 0

Views: 128

Answers (2)

Renatas M.
Renatas M.

Reputation: 11820

You have working deserialization code and question is actually not related with it. What you want is to access your deserialized object field.

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}"); 

Upvotes: 1

Michał Turczyn
Michał Turczyn

Reputation: 37367

It looks like you have ipBridge objects in your JSON (based on names used in JSON), from occurence of [, ] (square brackets) I can tell that it should be a list of those objects. Thus, it should be deserialized to List<ipBridge>.

Use this code:

var json = @"[{ ""id"":""001788fffe2e6479"",""internalipaddress"":""192.168.1.2""}]";
var deserialized = JsonConvert.DeserializeObject<List<ipBridge>>(json);

Upvotes: 0

Related Questions