var responseFromServer =
// lines split for readability
"{\"flag\":true,\"message\":\"\",\"result\":{\"ServicePermission\":true,"
+ "\"UserGroupPermission\":true}}";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var responseValue = serializer.DeserializeObject(responseFromServer);
responseFromServer值是获取webservice,然后如何获取JSON字符串值,如“flag”,“Servicepermission”??
词缀:对不起,用c#来做这件事。
答案 0 :(得分:5)
注意:JavaScriptSerializer实际上是我测试过的最慢的JSON Serializer。所以我不得不将其从my benchmarks中删除,因为它花了太长时间(慢了100倍)。
无论如何,使用ServiceStack.Text's JSON Serializer
轻松解决了这个问题var response = JsonSerializer.DeserializeFromString<Dictionary<string,string>>(responseFromServer);
var permissions = JsonSerializer.DeserializeFromString<Dictionary<string,string>>(response["result"]);
Console.WriteLine(response["flag"] + ":" + permissions["ServicePermission"]);
为了完整性,这也适用于ServiceStack.Text.JsonSerializer:
public class Response
{
public bool flag { get; set; }
public string message { get; set; }
public Permisions result { get; set; }
}
public class Permisions
{
public bool ServicePermission { get; set; }
public bool UserGroupPermission { get; set; }
}
var response = JsonSerializer.DeserializeFromString<Response>(responseFromServer);
Console.WriteLine(response.flag + ":" + response.result.ServicePermission);
答案 1 :(得分:-1)
if u are using jQuery u can do this
var json=jQuery.parseJSON(responseFromServer);
//acess
alert(json.ServicePermission);
if you are asing microsoft ajax do this
var json=Sys.Serialization.JavaScriptSerializer.deserialize(responseFromServer,true);
//acess
alert(json.ServicePermission);
在c#中像php我没见过任何将json转换为对象的方法。要在c#中进行转换,您必须先为此创建一个类。
对于你的情况,你可以这样做
//定义类
public class Response
{
public bool flag { get; set; }
public string message { get; set; }
public Permisions result { get; set; }
}
public class Permisions
{
public bool ServicePermission { get; set; }
public bool UserGroupPermission { get; set; }
}
var responseFromServer =
// lines split for readability
"{\"flag\":true,\"message\":\"\",\"result\":{\"ServicePermission\":true,"
+ "\"UserGroupPermission\":true}}";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var responseValue = serializer.Deserialize<Response>(responseFromServer);
//access
responseValue.result.ServicePermission