Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get JSON String value?

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 value is get a webservice, and then how to get the JSON string value, such as "flag","Servicepermission"??

affix: i'm sorry, using c# to do this.

like image 785
Net205 Avatar asked Aug 09 '26 16:08

Net205


1 Answers

Note: The JavaScriptSerializer is actually the slowest JSON Serializer I've ever benchmarked. So much so I've had to remove it from my benchmarks because it was taking too long (>100x slower).

Anyway this easily solved using 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"]);

For completeness this would also work with 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);
like image 60
mythz Avatar answered Aug 11 '26 06:08

mythz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!