Stefan
Stefan

Reputation: 585

get a c# object from json

I have this call

request.Content = new StringContent(json, Encoding.UTF8, "application/json");

and get back a json object like

{“Email”:"[email protected]",”Name”:”Stefan”}

How I get the value form the string back in an object? The user object is user.email and user.name .

Regards Stefan

Upvotes: 1

Views: 62

Answers (1)

hsh
hsh

Reputation: 1855

there are many ways to achieve this:

  1. you can use JSON.NET to work with json:

    JObject jObject = JObject.Parse(json);
    string Name = (string)jObject["Name"];
    string Email = (string)jObject["Email"];
    
  2. you can use JavascriptSerilizer

    JavaScriptSerializer json_serializer = new JavaScriptSerializer();
    User user = (User)json_serializer.DeserializeObject(json);
    
  3. or you can use DataContractJsonSerilizer like this:

    public static T Deserialize<T>(string json)
    {
      T obj = Activator.CreateInstance<T>();
      MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
      obj = (T)serializer.ReadObject(ms);
      ms.Close();
      return obj;
    }
    

Upvotes: 1

Related Questions