简体   繁体   中英

JSON to Array c#

I Have a JSON with this values

{"interface":"ALL",
 "dv":"1",
 "alarms":[{"Id":0,
            "Type":"URL",
            "Trigger":"facebook",
            "Output":"video"},
           {"Id":1,
            "Type":"URL",
            "Trigger":"twitter",
            "Output":"video"},
           {"Id":2,
            "Type":"URL",
            "Trigger":"ebay",
            "Output":"video"}
]}

And i would like parse this information to mi C# Code

I do this for Strings tags and works ok

JObject obj = JObject.Parse(json);
String value =(String) obj["dv"]; 

but i have an error for tag Array alarms. I've tried with:

Array value = null;
value =(Array) obj["alarm"]; 

but i get an error (Message=Can not convert Array to byte array. Source=Newtonsoft.Json).

Try convert your alarms into a JArray :

JArray value = null;
value = obj["alarms"] as JArray;

You could use JavaScriptSerializer for this.
For example:

JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, object> dict = jss.Deserialize<Dictionary<string, object>>(jsonString);

Using Json.Net

JArray value = null;
value = obj["alarms"] as JArray;

The casting should be JArray

Your json string has a reserved c# keyword: interface . Try changing this and see if it works.

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