How to parse a JSON object - c#

I have a method which is returning Json Result Like :
return Json(new { status = "error", message = "The organization cannot be deleted because contains transmitters!" });
Now I want to test with status and Message I have tried with this
var result = Controller.DeleteOrganization(2) as JsonResult;
Assert.AreEqual("error", result.Data.message);
I am getting Error:
object does not contain a definition for message
How can I resolve this Issue?

The Data is of type object and would not be exposing the property. Try assigning the Data property to a dynamic variable and then try accessing the property.
var result = Controller.DeleteOrganization(2) as JsonResult;
var data = JsonConvert.SerializeObject(result.Data);
var deserializedData = JsonConvert.DeserializeObject<dynamic>(data);
Assert.AreEqual("error", deserializedData.status);
If that does not work then I gave an answer here and here that you can adapt to your problem.

Use json2csharp.com convert JSON to C#
Create a class file put the code
Add the Newtonsoft.Json library to your project using the Nuget Package Manager
Convert the JSON
RootObject r = JsonConvert.DeserializeObject(json);

Related

Why is JObject.Parse creating an object inside an object from a string?

I have a string value:
var responseString = {"ErrorType":"ServerError","Message":"Incoming data error.","Properties":null}
When I call JObject.Parse(responseString);, I get the following dynamic object:
{{
"ErrorType": "ServerError",
"Message": "Incoming data error.",
"Properties": null
}}
Why is JObject creating a dynamic object that is an object wrapped in an object? I was hoping to write code to access the Message property such as responseMessage.Message as string, but that throws an error.
I just tried the following code in LinqPad:
var responseString = "{\"ErrorType\":\"ServerError\",\"Message\":\"Incoming data error.\",\"Properties\":null}";
dynamic responseMessage = JObject.Parse(responseString);
var msg = (string) responseMessage.Message;
msg.Dump();
In the output, I get the desired Incoming data error. string, so it looks like it is doing what it should. How does your code look? And what version of Json.NET are you using? Also, it is NOT possible to use as to convert to string, as this will return null, since the value is a JToken. You need the explicit cast.

pulling a python list out of a json object and converting it to something usable in C#

I have a python server that sends a list of strings as a json object to a C# client. On the client end I have this code to deserialize the object:
try
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
textBox4.Text = jsonObject.ToString();
}
catch (Exception e){
textBox2.Text = e.ToString();
}
What i'm getting as a result is: "System.Object[]"
Ideally I would like to put the contents of the list into an array.
can anyone point me in the right direction?
You are getting an array of generic objects, however I supose that you don't want this and you prefer getting a more usable result, so:
Create a class with the object's properties (for example: id, name, etc.). You can use this page in order to autogenerate the class.
Then deserialize the input into objects of the class that you have created in the first step, with the following code:
MyNewClass myNewClassList = serializer.Deserialize<MyNewClass>(sr.ReadToEnd());
I hope this can help you
Edit
This is a complete example created with the new information that you tell me in the comments:
var json = "[\"file0\",\"file1\",\"file2\",\"file3\",\"file4\",\"file5\"]";
var serializer = new JavaScriptSerializer();
var files = serializer.Deserialize<List<String>>(json);

Double Label for Json Property C#

I need to pass a Json object to an API, but the API requires the Json properties to have a double label of sorts, such as:
{
"name:id":"1234"
}
However, using Newtonsoft.Json.Linq, I can't get this to format the label exactly. Here is what I've tried so far (which throws an error)
dynamic json= new JObject();
json.name.id = "1234";
Doing
json.id = "1234";
Works just fine. I have also tried
json.name = new JProperty("id", "1234");
Which also throws an error. I have also tried hard coding the json file as a single string and converting that to a JObject, which also threw an error. Is what I'm trying to do possible or am I missing something? Is there another Json package I could use that would support what I want to do?
Use JObject's string indexer notation.
dynamic json = new JObject();
json["name.id"] = "1234";
Since the json is essentially built as a key/value pair, using a string indexer can allow you to overcome atypical property names.
There multiple ways to achieve that.
You can use JsonProperty attribute and specify the property name as name:id like:
class MyClass
{
[JsonProperty("name:id")]
public string Name_Id { get; set; }
}
and then you can do:
MyClass obj = new MyClass();
obj.Name_Id = "1234";
var strJson = JsonConvert.SerializeObject(obj);
and you will get back:
{"name:id":"1234"}

Assigning Json object properties to a model

I'm matching about 90 properties from a nested JSON-Object to a model class using dynamics and JObject.Parse:
dynamic json = JObject.Parse(JsonObjectAsString);
return new Foo() {
prop1 = json.summer.temperature,
prop2 = json.winter.temperature,
...
prop100 = json.autumn.temperature
}
This is very slow, but only on the first run. On a second run, a new JSON-Object is fetched (same structure but different values), and this one is assigned to the corresponding model properties in no time.
Why is that? What can I do to speed up the first run?
Edit: I've already set the build type to "Release".
You can parse your JSON object direct to model using newtonsoft nuget package.
var objData = JsonConvert.DeserializeObject<MyData>(yourjsondata);
You can get your model class from json data from http://json2csharp.com/
You can convert using dynamic object as well
var objData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonString);
Or without specifying model calss
var objData = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);

Deserialize JSON to anonymous object

In C#, I have successfully serialized an anonymous object into JSON by use of code like this...
var obj = new { Amount = 108, Message = "Hello" };
JavaScriptSerializer serializer = new JavaScriptSerializer();
String output = serializer.Serialize(obj);
However, what I would like to be able to do later is to deserialize the JSON string back into an anonymous object. Something like this...
var obj2 = serializer.Deserialize(output, object);
But the serializer.Deserialize() method requires a second parameter that is the type of object it will deserialize to.
I tried this...
var obj2 = serializer.Deserialize(output, obj.GetType());
But this produces an error:
No parameterless constructor defined for type of '<>f__AnonymousType0`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
I'm not sure what this error means.
how about dynamics, the fastest way I see is this:
dynamic myObject = JsonConvert.DeserializeObject<dynamic>(output);
decimal Amount = Convert.ToDecimal(myObject.Amount);
string Message = myObject.Message;
Note:
You will need Newtonsoft.json.dll reference
JSON.Net is a powerful library to work with JSON in .Net
There's a method DeserializeAnonymousType you can tap in to.
Update: Json.Net is now included with ASP.Net, however my latest favorite that I use is JsonFX. It's got great linq support as well, check it out.
Update 2: I've moved on from JsonFX, and currently use ServiceStack.Text, it's fast!
How about using the DeserializeObject method, it does not require a specific type. This also solved a similar SO question. The method deserializes to a Dictionary<string, object> containing name/value pairs.
Update: to clarify the error you get when doing this:
var obj2 = serializer.Deserialize(output, obj.GetType());
Given the type of obj, Deserialize will try to create a new instance of the type using a default constructor. Anonymous types in C# does not have a public parameterless constructor, and thus the operation fails.
This can also be done using the in-built JavaScriptSerializer, as follows:
object result = new JavaScriptSerializer().DeserializeObject(JSONData);
This will return an object[] instance, with Key-Value pairs.
Recently I have been using the awesome JsonFx.Net library and I've come to appreciate what it does. You can use Nuget Package Manager to install it right inside Visual Studio.
The code goes like this,
var reader = new JsonReader();
string input = #"{ ""first"": ""Foo"", ""last"": ""Bar"" }";
var template = new { first=String.Empty, middle=String.Empty, last=String.Empty };
var output = reader.Read(input, template);
As you can see you can even specify the template for Anonymous Type.
if you use Newtonsoft.Json you can try DeserializeAnonymousType method
var obj1 = new { Amount = 108, Message = "Hello" };
var json=JsonConvert.SerializeObject(obj1);
// or as well
var json= "{ \"Amount\" : 108, \"Message\" : \"Hello\" }";
//Deserialization
var definition = new { Amount = 0, Message = "" };
//obj2 type is "anonymous"
var obj2 = JsonConvert.DeserializeAnonymousType(json,definition);
result
{ Amount = 108, Message = "Hello" }
If you do not want to manually provide the type i found the easyest way is just:
var jsonString = JsonHelper.SerializeObject(item);
ExpandoObject obj = JsonHelper.DeserializeObject<ExpandoObject>(jsonString);
You can use JObject instead to deserialize the JSON string:
using Newtonsoft.Json.Linq;
string output = "{\"Amount\" = 108, \"Message\" = \"Hello\"}";
var amount = JObject.Parse(output)["Amount"];

Categories

Resources