0

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?
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
jck91
  • 11
  • 1
  • 1
    Possible duplicate of [How to Deserialize JSON data?](https://stackoverflow.com/questions/18242429/how-to-deserialize-json-data) – SᴇM Oct 16 '18 at 08:30
  • use visual studio to automatically create the class for you. add the json into your clipboard and insert it with vs as a new class – slow Oct 16 '18 at 08:31
  • I'm mean it's bad but you could use `ipBridge[i].InternalIpAddress ` – slow Oct 16 '18 at 08:33
  • also, your line where you use `Select()` is used wrong. you don't save the list anywhere. it returns a new list but you through it away. Your code is all wrong – slow Oct 16 '18 at 08:34

2 Answers2

1

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}"); 
Renatas M.
  • 11,694
  • 1
  • 43
  • 62
0

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);
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69