Sachu Sachu - 3 years ago 143
C# Question

how to seperate each data from a php post reply result

I am calling a PHP function from c# as below

using (var client = new WebClient())
string URL = "http://site.or/services/LoadMemberData.php";

NameValueCollection formData = new NameValueCollection();
formData["id"] = "123";

byte[] responseBytes = client .UploadValues(URL, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(responseBytes);


once it completed the
contain the some error message in case of error or details of the member in case of success
as below

{"result":{"success":true,"message":"","errorcode":0},"response":{"id":"123","full_name":"tom Vin","mobile_no":"02343434","phone_no":null,"country_code":"123312","country_of_residence":"","email":"","passport_no":"hedf"}}

how can i seperate the result into variables?

Answer Source

You can generate your models by json2csharp tool like this:

public class Result
    public bool success { get; set; }
    public string message { get; set; }
    public int errorcode { get; set; }

public class Response
    public string id { get; set; }
    public string full_name { get; set; }
    public string mobile_no { get; set; }
    public object phone_no { get; set; }
    public string country_code { get; set; }
    public string country_of_residence { get; set; }
    public string email { get; set; }
    public string passport_no { get; set; }

public class RootObject
    public Result result { get; set; }
    public Response response { get; set; }

Then deserialize your input with Newtonsoft.Json library:

var input =
    "{\"result\":{\"success\":true,\"message\":\"\",\"errorcode\":0},\"response\":{\"id\":\"123\",\"full_name\":\"tom Vin\",\"mobile_no\":\"02343434\",\"phone_no\":null,\"country_code\":\"123312\",\"country_of_residence\":\"\",\"email\":\"\",\"passport_no\":\"hedf\"}}";
var result = JsonConvert.DeserializeObject<RootObject>(input);

EDIT: Based on @Sir Rufo comment: you can generate your models with This site allow you to generate data annotations like this:

public class Response
    public string FullName { get; set; }

so you can have a convenient C# naming for your fields

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download