Getting a specific field from a JSON string without deserializing in C# - 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

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"];

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"]);

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;

Related

how to deserialize an anonymus object in c# [duplicate]

Is it possible to return a dynamic object from a json deserialization using json.net? I would like to do something like this:
dynamic jsonResponse = JsonConvert.Deserialize(json);
Console.WriteLine(jsonResponse.message);
Json.NET allows us to do this:
dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");
Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);
Output:
1000
string
6
Documentation here: LINQ to JSON with Json.NET
See also JObject.Parse and JArray.Parse
As of Json.NET 4.0 Release 1, there is native dynamic support:
[Test]
public void DynamicDeserialization()
{
dynamic jsonResponse = JsonConvert.DeserializeObject("{\"message\":\"Hi\"}");
jsonResponse.Works = true;
Console.WriteLine(jsonResponse.message); // Hi
Console.WriteLine(jsonResponse.Works); // True
Console.WriteLine(JsonConvert.SerializeObject(jsonResponse)); // {"message":"Hi","Works":true}
Assert.That(jsonResponse, Is.InstanceOf<dynamic>());
Assert.That(jsonResponse, Is.TypeOf<JObject>());
}
And, of course, the best way to get the current version is via NuGet.
Updated (11/12/2014) to address comments:
This works perfectly fine. If you inspect the type in the debugger you will see that the value is, in fact, dynamic. The underlying type is a JObject. If you want to control the type (like specifying ExpandoObject, then do so.
If you just deserialize to dynamic you will get a JObject back. You can get what you want by using an ExpandoObject.
var converter = new ExpandoObjectConverter();
dynamic message = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, converter);
I know this is old post but JsonConvert actually has a different method so it would be
var product = new { Name = "", Price = 0 };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, product);
Yes you can do it using the JsonConvert.DeserializeObject. To do that, just simple do:
dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);
Note: At the time I answered this question in 2010, there was no way to deserialize without some sort of type, this allowed you to deserialize without having go define the actual class and allowed an anonymous class to be used to do the deserialization.
You need to have some sort of type to deserialize to. You could do something along the lines of:
var product = new { Name = "", Price = 0 };
dynamic jsonResponse = JsonConvert.Deserialize(json, product.GetType());
My answer is based on a solution for .NET 4.0's build in JSON serializer. Link to deserialize to anonymous types is here:
http://blogs.msdn.com/b/alexghi/archive/2008/12/22/using-anonymous-types-to-deserialize-json-data.aspx
If you use JSON.NET with old version which didn't JObject.
This is another simple way to make a dynamic object from JSON:
https://github.com/chsword/jdynamic
NuGet Install
PM> Install-Package JDynamic
Support using string index to access member like:
dynamic json = new JDynamic("{a:{a:1}}");
Assert.AreEqual(1, json["a"]["a"]);
Test Case
And you can use this util as following :
Get the value directly
dynamic json = new JDynamic("1");
//json.Value
2.Get the member in the json object
dynamic json = new JDynamic("{a:'abc'}");
//json.a is a string "abc"
dynamic json = new JDynamic("{a:3.1416}");
//json.a is 3.1416m
dynamic json = new JDynamic("{a:1}");
//json.a is integer: 1
3.IEnumerable
dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
//And you can use json[0]/ json[2] to get the elements
dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
//And you can use json.a[0]/ json.a[2] to get the elements
dynamic json = new JDynamic("[{b:1},{c:1}]");
//json.Length/json.Count is 2.
//And you can use the json[0].b/json[1].c to get the num.
Other
dynamic json = new JDynamic("{a:{a:1} }");
//json.a.a is 1.
Yes it is possible. I have been doing that all the while.
dynamic Obj = JsonConvert.DeserializeObject(<your json string>);
It is a bit trickier for non native type. Suppose inside your Obj, there is a ClassA, and ClassB objects. They are all converted to JObject. What you need to do is:
ClassA ObjA = Obj.ObjA.ToObject<ClassA>();
ClassB ObjB = Obj.ObjB.ToObject<ClassB>();

Serialize string to JSON without \0027

A fairly straightforward question. I have the following code
var json = new JavaScriptSerializer();
var test = json.Serialize("'");
Now, Visual Studio local variable watch shows that test contains a string of value "\"\\u0027\"". Is it possible, using build in ASP.NET to make Serialize(); return serialized string without \0027 format?
The desired result for test would be "\"\'\""
Thanks!
As the commenters mentioned, this really shouldn't matter because \u0027 literally represents a single quote in Javascript.
However, if this bothers you, you may want to try using JSON.NET, which leaves single-quotes in encoded strings as they are.
Try the following
var json = JsonConvert.SerializeObject(obj);
You have to use this expression to replace your JSON string after it's serialized. Here is a sample of my code along with a function I use when giving a json output.
string json = obj.ToJSON();
json = System.Text.RegularExpressions.Regex.Unescape(json);
File.WriteAllText("<DirectoryFile>.json", json);
public static string ToJSON(this object obj)
{
var serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(obj);
}

Newton.JSON convert dynamic object to JObject instead of dynamic object

string result ="{"AppointmentID":463236,"Message":"Successfully Appointment Booked","Success":true,"MessageCode":200,"isError":false,"Exception":null,"ReturnedValue":null}"
dynamic d = JsonConvert.DeserializeObject<dynamic>(result);
d.GetType () is Newtonsoft.Json.Linq.JObject
so how to deserialize it to dynamic object instead of JObject
It's not quite clear what is not working for you and why you care about the return type but you could directly access the properties of the deserialized object like this:
string result = #"{""AppointmentID"":463236,""Message"":""Successfully Appointment Booked"",""Success"":true,""MessageCode"":200,""isError"":false,""Exception"":null,""ReturnedValue"":null}";
dynamic d = JsonConvert.DeserializeObject<dynamic>(result);
string message = d.Message;
int code = d.MessageCode;
...
You probably want something like
var values = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);
This might also suit your needs (untested)
dynamic d = JsonConvert.DeserializeObject<ExpandoObject>(json);

How to cast json object into a string

Here i'm having json string and i wanted to get one perticular key and value from this json string.So I have used javascript serializer for that.
Below is the code which i have used in C#.Net.
string strProfile = fbApi.GetForStr("/statefarm/feed/");
var jss = new JavaScriptSerializer();
var dictionary = (IDictionary<string, object>)jss.DeserializeObject(strProfile);
object keyvalue = (object)dictionary["paging"];
string data = keyvalue.ToString();
When i do this I'm not able to fetch the keyvale pair from the jsonstring. If i write
string keyvalue = (string)dictionary["paging"];
instead of
object keyvalue = (object)dictionary["paging"];
string data = keyvalue.ToString();
getting on exception called
object of type 'system.object ' to type 'system.string '
What to do for this and how it can bne written.
I am assuming that you are using the Facebook API using some SDK / your custom code here. JSON.NET is the best way to go unless you don't want to end up in the unholy mess of Key Value paired JSON.
Try this.
var api = new FacebookClient
{
AccessToken = accessToken,
AppId = AppID,
AppSecret = AppSecret
};
dynamic result = api.Get("me/posts");
string JsonConvert.SerializeObject(result, new KeyValuePairConverter())
or to avoid confusion, simply add this to your code
object keyvalue = (object)dictionary["paging"];
JsonConvert.SerializeObject(keyvalue , new KeyValuePairConverter());
The NewtonSoft.Json.dll is also available as a Nuget package.

Periods in the name of c# dynamic ExpandoObjects?

Maybe this is a silly question, but I'm working on a project that wants me to generate some JSON that looks like this:
{'action.type':'post', 'application':APP_ID}
In C#, I'm trying to create this "action.type" attribute, with the value of "post". How would I do that? Here's how I've typlically been creating stuff like:
dynamic ActionSpec = new ExpandoObject();
ActionSpec.SomeParam = "something";
ActionSpec.id = 12345;
I can't go "ActionSpec.action.type", because that will not output the desired "action.type".
Does this make sense?
Thanks!
You could try populating it via the dictionary:
IDictionary<string, object> expandoDictionary = ActionSpec;
expandoDictionary["action.type"] = "post";
However, I wouldn't be at all surprised if it rejected that as an invalid identifier.
Using Json.Net
JObject jObj = new JObject();
jObj["action.type"] = "post";
jObj["application"] = "APP_ID";
var json = jObj.ToString();

Categories