How to get value from dynamic object? - c#

I need otp value from the following dynamic otp json element I am recieving in Web API Controller. I have tried a lot of things but couldn't find.
This is how I receive in controller
Quick watch window

As your Quick Watch shows:
When you use dynamic here, it won't be deserialized to an object with the properties in json, but will return a JsonElement.
You can use its methods to parse the json as you like. Meanwhile you can just receive it like [FromBody] JsonElement opt.

Related

How to get http post request body without property in c#

I am creating an API. Where I have to accept JSON data. I found the JSON not properly fit with my property class. In this scenario how should I get data from post request?
I have tried with WEB API but it's showing null error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
You cannot always change the class like #GuruStron suggests. Because it could have dependencies on other parts of the program.
What you should do : Customize your JSON parser
You probably already use Newtonsoft to parse your incoming body request into your class. Now what you need is to customize that parser so it fit your need.
Here is the doc: How to create a custom JsonCoverter
If you don't use Newtonsoft you probably use default System.TextJson in that case here are the docs
No matter which "parser" you use, you'll probably find an equivalent on the web
Please provide more details (and some code) for a more precise answer.
I don't know if you are receiving the json via an HttpClient, but in the case you can use ExpandoObject or dynamic as read target from the content.
es.
var response = await httpClient.GetAsync(url);
var result = await response.Content.ReadFromJsonAsync<dynamic>();
or
var result = await response.Content.ReadFromJsonAsync<ExpandoObject>();
In any case, case the deserialization to dynamic or ExpandoObject could work also from a string (see this).

Invalid JSON when parsing objects containing html as a string property

I've got a controller action that just displays a JSON result: http://pkssblog-stage.azurewebsites.net/BlogPosts/GetAll. The object has a property called Content which is basically the HTML content of a post.
The problem is I always get invalid JSON exceptions when parsing it using the JsonObject.Parse in WinRT, the JSON.parse within a browser console or even JSON validators online.
The weird thing is that I don't get issues when I turn it into a javascript object via the console through var x = jsonstringarray;
I get in trouble with this specific property (as noted by the online validators):
"Content":"\u003cbr\u003eMicrosoft Azure Storage provides many services...
Any ideas?

Does Web API automatically convert any properties of type Object or object to JSON?

I'm making a request from a Web API Client passing an object that has a single property of type object. The class is called WebRequestObject so in my front end controller I create a new instance of WebRequestObject and pass it an object of whatever type I want. For this example I will use MyClass.
So...
var reqObj = new WebRequestObject(new MyClass());
then
myWebApiClient.PostAsJsonAsync('someUrl', reqObj);
Now on my Web API Controller Method I get the WebRequestObject parameter and the data is correct, but instead of being an object it's converted to a JSON string for some reason?
Is this default behavior? If so does anyone have suggestions as how to stop this or a workaround?
Edit 1: A little more infor the PostAsJsonAsync takes an interface as it's second parameter and all my models implement this interface.
Edit 2: I realize the docs say this: Sends a POST request as an asynchronous operation, with a specified value serialized as JSON. That being said I'v tested having a different type of property on my WebRequestObject and it gets deserialized just fine. I guess it doesn't deserialize to type of object...
I've tested having a different type of property on my WebRequestObject
and it gets deserialized just fine. I guess it doesn't deserialize to
type of object...
This is because a string is an object. Since the api controller method is not being specific about how to convert the data into a CLR object, and the raw data sent over the wire is a json string, and a string is an object, it's just keeping the raw form of the request parameter.
In other words, you can always upcast a string to an object.

c# MVC 4 Web API - Return object from JSON string

I'm working with the mvc 4 web api to build a service layer that will always return JSON.
My api method calls actually call another service which returns a JSON object. I then want to just pass this JSON object back as my return object, but I'm not sure what return type to use.
If I use string, it wraps the JSON object in quotes.
By the way, I already changed the default MediaTypeFormatter to be JSON.
Here is an example of the JSON object:
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"indent":"on",
"q":"id:100001",
"wt":"json"}},
"response":{"numFound":1,"start":0,"docs":[
{
"Header":"Test Header",
"MaxPrice":515.0,
"ApartmentName":"Apartment 1",
"MaxBathrooms":4.0,
"Pool":true,
"MinBathrooms":2.0,
"MaxBedrooms":4,
"CoveredParking":false}]
}}
In the Beta release, you can use JsonValue (from the System.Json namespace). If your call to the other service returns a string which contains the JSON data, then you can call JsonValue.Parse to load that into the object to return.
In the RC release (or in the current bits from http://aspnetwebstack.codeplex.com) you can use the JToken object (from the Newtonsoft.Json.Linq namespace) - the default JSON serializer and JSON DOM are now coming from the JSON.NET library.
So, the issue turned out to be that I was taking a serialized json object and then reserializing in the JavaScriptSerializerFormatter that overrides the default xml MediaTypeFormatter.
I fixed the issue by returning the JsonValue and then checking the type and not reserializing it.
Thanks carlosfigueira for the help finding this.
To return Json from MVC, use JsonResult. You can first convert the string to an object using DataContractJsonSerializer.
http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/

Reading JavaScriptSerializer c# back in javascript

In one of my webservice methods I serialized my object calling JavaScriptSerializer.serilize in c#. Now when that returns a string to my javascript I would like to be able to call the properties from the object. I tried, results.d.ID but that did not work. Here is what it returns. Thanks for any help.
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
Inventory item = Inventories.GetInventoryByID(inventoryID);
string jsonObject = oSerializer.Serialize(item);
For example I would like to get the ID out. how would I do that?
{"d":"{\"ID\":\"589652cf-2ccd-49c1-b457-f2793a2a2424\",\"Brand\":{\"ID\":\"b728281b-cf3c-4ee0-ba3d-a3573b886b14\",\"Name\":\"Puma1\",\"ParentBrand\":null,\"BrandChildren\":{\"IsValueCreated\":false,\"Value\":[]}},\"DateAdded\":\"\\/Date(1327695794000)\\/\",\"AddedBy\":{\"ID\":\"d6e1f2e7-f8d1-4809-aadd-4cacd5c2bc43\",\"Email\":\"mojo#yahoo.com\",\"FirstName\":\"maurice\",\"MiddleInitial\":\"l\",\"LastName\":\"bachelor\",\"Address\":\"111 main st\",\"Phone\":\"2162330333\",\"IsAdmin\":true,\"DateJoined\":\"\\/Date(-62135578800000)\\/\",\"HasPurchased\":false,\"AgreeTerms\":true,\"LastPurchaseDate\":null,\"Password\":\"maurice\",\"CompanyName\":\"sneakers101\",\"AllowEmail\":false,\"PurchaseOrders\":{\"IsValueCreated\":false,\"Value\":[]}},\"LastUpdated\":\"\\/Date(1327688594000)\\/\",\"Instock\":true,\"NumberInStock\":12,\"MainPictureUrl\":\"\",\"AlternativePictureUrl\":\"\",\"ThumbNailUrl\":\"\",\"Price\":12.99,\"Like\":0,\"Discount\":1,\"ItemReleaseDate\":\"\\/Date(568011600000)\\/\",\"ItemCondition\":\"Great\",\"Size\":12,\"ItemNumber\":3,\"IsFavorite\":false,\"Details\":\"test Details\",\"Name\":\"Test\"}"}
As Inerdial said you have strange nested JSON value. If data is in format you actually want - use JSON.parse to re-parse values like:
JSON.parse(results.d).ID.
Here's what it's all about: asp.net's ajax d
var jsonObj = theObject; // Assuming it is parsed somehow
var embeddedJsonObj = $.parseJSON( jsonObj.d );
// embeddedJsonObj.ID is the ID you need.
Demo
It looks like your underlying problem is the manually JSON serialization.
Since ASP.NET will automatically JSON serialize the result of your method, your manually serialized jsonObject string is then getting serialized a second time. That's why Alexei's answer works. jQuery deserialized it once, leaving you with a .d property containing a JSON string, and then JSON.parse() deserialized that inner JSON string.
However, that is doubly inefficient because your data is being serialized twice and deserialized twice. Instead, just do this:
[WebMethod]
public Inventory GetInventoryById(inventoryID) {
return item = Inventories.GetInventoryByID(inventoryID);
}
Then, ASP.NET will return JSON that looks like this:
{"d": {"ID": "589652cf-2ccd-49c1-b457-f2793a2a2424", /* the rest of your data here */ }}
Which jQuery (assuming you're using jQuery) will automatically JSON.parse() since ASP.NET responds with an application/json Content-Type, and then you'll be able to index into like results.d.ID.

Categories