简体   繁体   中英

Deserialize Json String to C# object

I'm trying out the Philips Hue lights api for the first time and I have a few questions on how to deserialize the json string to a C# object. I'm trying this out for the Xamarin.iOS app I'm working on.

Here's my method that would fetch the light data from around me:

private string getLights()
{
    var url = APIURL + APIKey + LightsEndPoint ; 

    var request = WebRequest.Create(url);
    request.ContentType = "application/json";
    request.Method = "GET";

    using (var response = request.GetResponse() as HttpWebResponse)
    {
        if (response.StatusCode != HttpStatusCode.OK)
            Console.Out.WriteLine(
                "Error fetching data. Server returned status code: {0}",
                response.StatusCode);

        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var content = reader.ReadToEnd();

            if(string.IsNullOrWhiteSpace(content))
            {
                Console.WriteLine("Response contained empty body...");
            }
            else
            {
                Console.WriteLine("Response Body: \r\n {0}", content);
                var items = JsonConvert.DeserializeObject <Light> (content);            
            }
            return content; 
        }
    }
}

Where Light is:

public class Light
{
    public Light()
    { }

    public string LightName { get; set;}

    [JsonProperty("state")]
    public string IsOn { get; set; }

    [JsonProperty("sat")]
    public int Saturation { get; set; }

    [JsonProperty("bri")]
    public int Brightness {get;set;} 

    [JsonProperty("hue")]
    public int Hue { get; set; }
}

The problem I'm having now is my items object is always empty, null values even though I'm properly getting content json string.

My json string looks like this:

{  
    "1":{  
        "state":{  
            "on":true,
            "bri":254,
            "hue":20000,
            "sat":100,
            "effect":"none",
            "xy":[  
                 0.4146,
                 0.4155
            ],
            "ct":299,
            "alert":"none",
            "colormode":"hs",
            "reachable":true
        },
        "type":"Extended color light",
        "name":"Hue color lamp 1",
        "modelid":"LCT007",
        "manufacturername":"Philips",
        "uniqueid":"00:17:88:01:10:26:3f:12-0b",
        "swversion":"5.38.1.14919"
    },
    "2":{  
        "state":{  
            "on":false,
            "bri":254,
            "hue":50000,
            "sat":254,
            "effect":"none",
            "xy":[  
                0.2468,
                0.0843
            ],
            "ct":153,
            "alert":"none",
            "colormode":"hs",
            "reachable":true
        },
        "type":"Extended color light",
        "name":"Hue color lamp 2",
        "modelid":"LCT007",
        "manufacturername":"Philips",
        "uniqueid":"00:17:88:01:10:5d:fd:f6-0b",
        "swversion":"5.38.1.14919"
    },
    "3":{  
        "state":{  
            "on":true,
            "bri":254,
            "hue":10000,
            "sat":254,
            "effect":"none",
            "xy":[  
                0.5711,
                0.3986
            ],
            "ct":500,
            "alert":"none",
            "colormode":"hs",
            "reachable":true
        },
        "type":"Extended color light",
        "name":"Hue color lamp 3",
        "modelid":"LCT007",
        "manufacturername":"Philips",
        "uniqueid":"00:17:88:01:10:26:3d:17-0b",
        "swversion":"5.38.1.14919"
    }
}

The problem I'm having is light is indicated by a numerical value and I'm not sure how to split the json string to populate my c# object.

Basically, I'm having issues converting the json string to c# object for api stream for Xamarin.iOS app.

Your model should look like this

public class Light
{

    public Light()
    {

    }

    [JsonProperty("name")]
    public string LightName { get; set;}

    [JsonProperty("state")]
    public State State { get; set; }
}

public class State 
{
    public State() 
    {
    }

    [JsonProperty("on")]
    public bool IsOn { get; set; }

    [JsonProperty("sat")]
    public int Saturation { get; set; }

    [JsonProperty("bri")]
    public int Brightness {get;set;} 

    [JsonProperty("hue")]
    public int Hue { get; set; }
}

And deserialization call should look like this

JsonConvert.DeserializeObject<Dictionary<string, Light>>(content);

Where the key of the dictionary is the numbers and value is the light model you want to get.

I generated a class with json2csharp :

public class State
{
    public bool on { get; set; }
    public int bri { get; set; }
    public int hue { get; set; }
    public int sat { get; set; }
    public string effect { get; set; }
    public List<double> xy { get; set; }
    public int ct { get; set; }
    public string alert { get; set; }
    public string colormode { get; set; }
    public bool reachable { get; set; }
}

public class RootObject
{
    public State state { get; set; }
    public string type { get; set; }
    public string name { get; set; }
    public string modelid { get; set; }
    public string manufacturername { get; set; }
    public string uniqueid { get; set; }
    public string swversion { get; set; }
}

then I called this code:

var a = JsonConvert.DeserializeObject<Dictionary<string, RootObject>>(json);

and the result was this:

在此处输入图片说明

As mentioned, your model structure does not match that of the json's. You need to properly nest the properties accordingly. I threw together an example, though certain data types I was unsure of I simply used a string(Which should be fine).

Light.cs

public class Light
{
    public string LightName { get; set; }

    [JsonProperty("state")]
    public State LightState { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("modelid")]
    public string ModelId { get; set; }

    [JsonProperty("manufacturername")]
    public string Manufacturer { get; set; }

    [JsonProperty("uniqueid")]
    public string UniqueId { get; set; }

    [JsonProperty("swversion")]
    public string SwVersion { get; set; }
}

State.cs

public class State
{
    [JsonProperty("on")]
    public bool IsOn { get; set; }

    [JsonProperty("bri")]
    public int Brightness { get; set; }

    [JsonProperty("hue")]
    public int Hue { get; set; }

    [JsonProperty("sat")]
    public int Saturation { get; set; }

    [JsonProperty("effect")]
    public string Effect { get; set; } // Just making it a string for now

    [JsonProperty("xy")]
    public double[] XY { get; set; }

    [JsonProperty("ct")]
    public int CT { get; set; }

    [JsonProperty("alert")]
    public string Alert { get; set; } // Just making another string for now

    [JsonProperty("colormode")]
    public string ColorMode { get; set; } // Hey, it's another string for now

    [JsonProperty("reachable")]
    public bool Reachable { get; set; }
}

Then to deserialize:

var items = JsonConvert.DeserializeObject<Dictionary<string, Light>> (content);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM