Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

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

like image 602
slaw Avatar asked May 18 '16 05:05

slaw


2 Answers

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"];
like image 76
YetAnotherCoder Avatar answered Nov 15 '22 01:11

YetAnotherCoder


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"]);
like image 29
Alexander Petrov Avatar answered Nov 15 '22 00:11

Alexander Petrov