user1114720
user1114720

Reputation: 71

Can't parse a JSON Response

I have a very simple response from a Json request, however I can't seem to find a easy way to parse it. I only find tutorials that use classes of third party's. I want to use the native functionality of .NET 3.5 writing in C# to interpret the response. Can anybody help, please?

{
    "id": "10000",
    "key": "TST-24",
    "self": "http://www.example.com/jira/rest/api/2/issue/10000"
}

Upvotes: 0

Views: 539

Answers (3)

I4V
I4V

Reputation: 35363

var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(json);
Console.WriteLine(dict["id"] + " " + dict["key"]);

Upvotes: 2

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22084

You can do it natively, provided you define server-level matching counterpart for json object:

[DataContract]
public class MyObject {
  [DataMember]
  public string id { get; set; }
  [DataMember]
  public string key { get; set; }
  [DataMember]
  public string self { get; set; }
}

public T FromJson<T>(string value) {
  var serializer = new DataContractJsonSerializer(typeof(T));
  T result;
  using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(value), false)) {
    result = (T)serializer.ReadObject(stream);
  }
  return result;
}

Upvotes: 2

Damien
Damien

Reputation: 8987

You can use the JavaScriptSerializer, it is available for .net 3.5.

Consider to use the very popular and easy Json.NET which can be installed with nu-get.

Upvotes: 2

Related Questions