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.
Related
I'm wrapping a third-party API in a controller (due to security hoops we have to jump through) and the API returns a JSON string.
I do some minor changes to the JSON string and want to return that string.
I don't see a way to do that with a JSONResult, as it requires an object, and returning JSON string is sent back as a string.
Am I stuck with using something like a ContentResult?
JSONLint.com says the modified JSON is valid. It starts with...
[{"Acknowledgment Start Date":null,"Additional Location Details":null,"Area Code":null,"Assign To Vendor":"No",...
If I use the Newtonsoft.Json.JsonConvert(), it does this to my JSON string...
[[[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],...
If I use JavaScriptSerializer, I get this again...
[[[[]],[[]],[[]],[[]],[[]],[[]],[[]],[[]],...
I suspect part of the problem is the null values in the JSON string.
Is there another solution? Are there issues with using a ContentResult that I'm not aware of?
Newtonsoft.Json.JsonConvert() serializes an object, it doesn't parse (AKA deserialize) it. What you're doing when you call Newtonsoft.Json.JsonConvert(jsonString) is you're saying "serialize this JSON string to JSON". So, you get a funky result.
You could instead parse the JSON, then make your modifications, then serialize it again. For example:
var myObject = Newtonsoft.Json.DeserializeObject<POCOClass>(jsonString);
myObject.Whatever = "123";
//... etc.
This of course after defining your POCO class like such:
public class POCOClass {
[JsonProperty(PropertyName = "Acknowledgment Start Date")]
public string AcknowledgmentStartDate { get; set; }
// etc.
}
Then when you're done, serialize it back:
jsonString = Newtonsoft.Json.JsonConvert(myObject) // or Newtonsoft.Json.SerializeObject(myObject)
Upon closer inspection, I had a couple of realizations.
The first being that the outputted JSON isn't valid because the quoted identifiers include spaces and colons. For example, this one from above.
... ,"Additional Location Details":null, ...
While I suspect this is the root of problems, I don't have the time to write a parser to make it proper JSON.
I will come back and write a tool to properly clean up the mess at some point, but right now I have another approach I'm doing.
I need a ASP.NET MVC controller, which receives anonymous object from JS in JSON to iterate thru its properties. I used to do this, receiving Dictionary<string, object>. But now one of values is Array, and insted of
receivedDictionary[Photos] = [object, object, object]
it gets it as
receivedDictionary[Photos[0]] = object, receivedDictionary[Photos[1]] = object, receivedDictionary[Photos[2]] = object
I get not one dictionary entry with key = Photos and value = array, but many entries with key = Photos[x] and value = object.
How do I get it as one entry in dictionary or is there any better way to get it as dynamic anonymous object and iterate thru its properties just like in JS?
UPD: JSON looks like this:
{"fields":{"TotalFloors":"9","HouseNumber":"10","Photos":[{"id":0,"ParentID":0,"OriginalUrl":"py4s1y3uyqu","OriginalExt":".jpg","ThumbUrl":"2hn04w2lzuu","FormatUrls":{"WH_109_82_Url":"4cwjarqudvo","WH_766_454_Url":"oofm5qo21rr"}},{"id":0,"ParentID":0,"OriginalUrl":"t3csgq20iro","OriginalExt":".jpg","ThumbUrl":"j1uwwburmse","FormatUrls":{"WH_109_82_Url":"gm4qoery1u2","WH_766_454_Url":"a3c20re3g1d"}}],"Details":"Other details"}}
Controller definition:
[HttpPut]
public ActionResult restId(string className, int id, Dictionary<string, object> fields)
{
....
}
The JsonValueProvider used by the DefaultModelBinder seems to be treating array in an odd fashion in this case (based on the source here), so even a dynamic will most likely have the issue. (Don't think you'll have this issue in MVC 6 however)
However, calling the JavascriptSerializer directly (which funny enough is what the default provider uses) produces the results you're after:
var js = new JavaScriptSerializer();
var res = js.DeserializeObject(#"{'TotalFloors':'9','HouseNumber':'10','Photos':[...],'Details':'Other details'}");
To address your issue you could either alter the parameter to a string and run the above code in your action (obviously replacing the JSON string with the parameter), just means the JSON you're submitting from the front end would need to look more like:
// wrapping the JSON object in quotes to stringify it
{ 'fields' : "{ 'TotalFloors': '9', 'HouseNumber': .... }" }
Otherwise you could implement a custom JsonValueProvider like the one proposed here: https://json.codeplex.com/discussions/347099
The custom value provider is probably the cleaner solution.
I am a C# developer and a newbi in Javascript.
I have one C# object and finally, in index.cshtml, I can get a string converted from the object via calling Json.Encode(obj)
The string is:
[
{
"Name":"CASE_A",
"Values":[99.8,99.9,99.9,99.8,99.8,96.3,22.3]
},
{
"Name":"CASE_B",
"Values":[99.8,99.8,99.8,96.3,22.3]
},
]
However, when I call JSON.parse(#TheString),I got:
Uncaught SyntaxError: Unexpected token &
The location of this error shows me this:
data = JSON.parse([{"Name":"CASE_A","Values":[99.8,99.9,99.9,99.8 ....
How can I fix this problem?
Thank you for the answers!
But still I got an error:
Uncaught SyntaxError: Unexpected token o
For simple testing, I used this:
#{
string tmp = "[{\"Name\":\"CASE_A\",\"Values\":[99.8,99.9,98.6]},{\"Name\":\"CASE_B\",\"Values\":[96.7,11.1]}]";
}
var data1 = JSON.parse(#Html.Raw(#tmp));
And source shows this line:
var data1 = JSON.parse([{"Name":"CASE_A","Values":[99.8,99.9,98.6]},{"Name":"CASE_B","Values":[96.7,11.1]}]);
I cannot see any "o" here.
Also, for making javascript object, Travis suggested to remove the key name before serialization. But in C#, all object must have its member name. All I can think of is string manipulation. Is there any better way to do so?
Razor will automatically escape HTML entities for you in an attempt to be helpful. You can disable this with Html.Raw:
JSON.parse(#Html.Raw(TheString))
For your second error, JSON.parse expects a string, but you are passing in an array. Your outputted js code has to look like this to work:
var data1 = JSON.parse("[{\"Name\":\"CASE_A\",\"Values\":[99.8,99.9,98.6]},{\"Name\":\"CASE_B\",\"Values\":[96.7,11.1]}]");
I also want to note that since you are injecting this object into your javascript code on the server side, there is no need to call JSON.parse at all. As long as you send properly formatted javascript to the client where it will be evaluated and run, then it doesn't matter how it's created on the server. Try this instead:
var data1 = #Html.Raw(#tmp);
You may try this using HtmlHelper.Raw method:-
data = JSON.parse(#Html.Raw(TheString));
Also check out DataContractJsonSerializer Class
Serializes objects to the JavaScript Object Notation (JSON) and
deserializes JSON data to objects. This class cannot be inherited.
Using the string will cause Razor to protect you from injection. If you are passing in json chances are that isn't an issue. Common practice is to use the Html.Raw helper
data = JSON.parse( #(Html.Raw(TheString)) );
OP's solution worked for me as well.
data = eval(JSON.parse(#Html.Raw(TheString)))
If you have a C# Object and want to use it in JavaScript as is, you can do:
var jsObject = #Html.Raw(JsonConvert.SerializeObject(TheString));
You'll need to add the nuget package and import the dll in _ViewImports.cshtml:
#using Newtonsoft.Json;
Hope it helps someone...
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/
i have a method that returns a list of serialized objects in my page code behind
private string Get()
{
JavaScriptSerializer jsonSerialiser = new JavaScriptSerializer();
string jsonString = SerializeToJason(UnavailabilityBusiness.Get(new DateTime()));
return jsonString ;
}
i would like to pass this serialized objects to javascript
function getJson()
{
??????
}
How do I do it?
You could write them out as a script, typically leveraging ClientScript.
You would want to take care to register the script so that it renders before the consuming script.
Looks like this guy wrote a utility class to do what you're trying to do (Code Project Link).
I have't really looked at it but you can get his source and have a look.
Good luck,
Patrick.