slaw
slaw

Reputation: 621

Getting a specific field from a JSON string without deserializing in C#

I currently have a REST app which returns a JSON string something like:

[{error: "Account with that email exists"}]

For when an error is thrown. I don't want to deserialize it into a custom "error" object, because it seems a bit wasteful and pointless. Is there a simple way to just extract a specific field out of a JSON string without making a custom class to reflect it.

Thanks

Upvotes: 10

Views: 34635

Answers (3)

Alexander Petrov
Alexander Petrov

Reputation: 14231

No need third party libraries. Use native JavaScriptSerializer.

string input = "[{error: \"Account with that email exists\"}]";
var jss = new JavaScriptSerializer();

var array = jss.Deserialize<object[]>(input);
var dict = array[0] as Dictionary<string, object>;
Console.WriteLine(dict["error"]);

// More short with dynamic
dynamic d = jss.DeserializeObject(input);
Console.WriteLine(d[0]["error"]);

Upvotes: 8

Mick
Mick

Reputation: 6864

Have a look at JObject.

dynamic obj = JObject.Parse("{ myerrors: [{error: \"Account with that email exists\"}] }");
var a = obj.myerrors[0];
string error = a.error;

Upvotes: 2

YetAnotherCoder
YetAnotherCoder

Reputation: 396

You have a couple of options if you don't want to create a custom class, you can deserialize to dynamic:

dynamic tmp = JsonConvert.DeserializeObject(yourString);
string error = (string)tmp.error;

Or deserialize to a dictionary:

var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>();
string error = dic["error"];

Upvotes: 19

Related Questions