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...
Related
I'm using Auth0 for a new app I'm writing using ASP.NET Core 1.0. It's working great so far, but I have bumped into something that is stumping me for some reason.
When the user logs in, Auth0 will pass claims back to my app. Auth0 has the ability to add custom data to the user, it is stored in JSON format and comes over as a list of claims.
One of the claims will look something like this:
Type "app_metadata"
Value "\"IsPublisherFor\":[\"p56\",\"p124\",\"p258\"]"
ValueType "JSON"
My question is, how would I convert that claim value into something I can work with? For example, the ability to do something like IsPublisherFor.Contains("p56");
I tried to pass the value to NewtonSoft.Json.JsonConvert.DeserializeObject(value) but it throws an exception. JsonReaderException: Additional text encountered after finished reading JSON content
Any way to convert this cleanly?
You probably need to wrap your JSON string in curly braces. You generally need a single top-level array or object to have valid JSON. Don't know about NewtonSoft, but using the JavascriptSerializer, this works:
var json = "{\"IsPublisherFor\":[\"p56\",\"p124\",\"p258\"]}";
var serializer = new JavaScriptSerializer();
stuff obj = serializer.Deserialize<stuff>(json);
With the following class defined to receive the data:
public class stuff
{
public string[] IsPublisherFor { get; set; }
}
I have a simple HTTPHandler pretending to be a Web Service
(platform constraints, don't judge me)
I want to be able to create a string array in javascript, stringify it, and send it in a REQUEST header to be consumed as a set of parameters.
My issue is, most of the deserialization methods require you to create a named object and deserialize the whole object. I just want the simple string, man.
var ar = [];
ar.push("one");
ar.push("two");
var arStr = JSON.stringify(ar);
//$Ajax() bla bla bla
//sends out as "[\"one\",\"two\"]"
I'm sure there is a simple answer, but so far I can't find it.
Addition
Platform constraints also limit me from using 3rd part libraries. Needs to be straight .NET
Your json is a string array/List. All you need is (using Json.Net)
List<string> list = JsonConvert.DeserializeObject<List<string>>(jsonstring);
If you are using JavaScriptSerializer
var list = new JavaScriptSerializer().Deserialize<List<string>>(jsonstring);
BTW: if you are using ajax, you don't need to stringify the object. Just post it as object. The library internally handles it, otherwise you may need double-deserialiazation at receiver end.
String.join(",", ar) if you can make sure that your strings don't contain the separator character.
My Problem is that when I browse to the service URL I see "key-value" pairs but I don't see the name of the array or object, I need the name because I want to use that service for android.
it looks like this:
My code looks like this:
1. In ValueController I have method:
[AcceptVerbs("GET", "POST")]
public List<BuzzMonitor.Web.Message> Search(string text, DateTime dateFrom, DateTime dateTo, [ModelBinder]List<int> themeIds, [ModelBinder]List<int> sourceIds)
{
MessageHandler mh = new MessageHandler();
List<BuzzMonitor.Web.Message> messages = null;
messages = mh.Search(text,dateFrom,dateTo,themeIds,sourceIds);
return messages;
}
2. In Global.asax I added:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Does anyone have an idea on what is missing when I don't see full JSON, and see just key:value pairs? Thank you for help!
I think you are thinking that you are not seeing the array name or class right? and that is an error?
The answer is NO.
Reason? Well, JSON was invented to share objects easily over network and the main goal was to make it independent of the underlying architecture -
http://www.json.org/
that is why you don't see array names or variable names, only the object notation. Thats JSON stands for Java Script Object Notation. It's the responsibility of the receiving side to re-construct the object from the data provided in json format.
in your case messages is an array with a list of data and so does the output -
[] means array and {} inside that means it has only one object in it.
EDIT: You can also use this to parse json -
http://developer.android.com/reference/org/json/JSONTokener.html
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.
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.