I am trying to do a JSON schema validation dynamically. We are taking the JSON from an uploaded file and trying to validate this is exact JSON or not. This is an On premise application.I cannot use JSON.net. I cannot install any other third party tools to validate this. I have tried two ways as below.
1.I used System.Web.Helper and Using the below code, i am getting the error
code :
var jsonstring = "{\"user\":{\"name\":\"asdf\",\"age\":\"26\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
var jsonObject = Json.Decode(jsonstring);
Error is "Attempt by method 'System.Web.Helpers.Json.Decode(System.String)' to access field 'System.Web.Helpers.Json._serializer' failed". I searched for solutions and found that we need to uncheck a check box in debug properties of solution.But this only works in Console application for me.But not working in our VS 2012 solution. Is there any way to solve this issue?
Next is, i tried to use JavaScriptSerializer as given below and successfully got the results in my objJson.
JavaScriptSerializer serializer = new JavaScriptSerializer();
string inputContent;
StreamReader inputStreamReader = new StreamReader(FileUploadControl.PostedFile.InputStream);
inputContent = inputStreamReader.ReadToEnd();
inputContent = inputContent.Replace("\r", "").Replace("\n", "").Replace("\t", "");
var objJson= serializer.Deserialize>(inputContent);
But when i am trying to get values of this resulted key values pair, i am getting error as in image. Error is Dynamic operations can only be performed in homogenous AppDomain. for this the solution found was to change the attribute "legacyCasModel=true" to "legacyCasModel=false" in web.config file. But as this is OnPremise application i cannot change this attribute.Please help on this.
Suggest you to have a look at this stackoverflow post
In nutshell what you want to do is :
Perform some basic checks i.e. if JSON string starts with either
'{'
or '['
Try to parse JSON string using JToken.Parse if there
is an exception while parsing simply log or display this to end user and move on ! you are just
trying to validate JSON string not attempting to clean it right ?
PS : Please do refer the linked question for greater details.
Related
I am trying to deserialize a file, none of the other solutions are working for me.
This is the code. I get the error on the 'customerList' line
using (StreamReader customerStreamReader =
new StreamReader(#"C:\...\ShoppingApplication\bin\Debug\Customer.xml"))
{
customerList = (List<Customer>)customerSerializer.Deserialize(customerStreamReader);
}
Look into using XDocument instead for it will be more robust in reporting errors, though the 0,0 location is a common one. Avoid using streams because they are so, .Net 2.
Here is an example:
var doc = XDocument.Load(#"C:\...\ShoppingApplication\bin\Debug\Customer.xml");
Console.WriteLine(doc);
Then extract what is needed from the actual nodes.
For anybody coming here from google:
If you do not want to use XDocument, then you must make sure that your .xml is NOT empty. Once I added something, I was able to deserialize it just fine. Hope this helps!
I have Json file connected with database: http://222.255.29.210:9000/pk/api/index.php/fbids
In code boder red: If I set "des = true" in database then tool run, if I set "des = false" then Winform c# close. Use Json data
I guess that your data on JSON come from database right ?
So, use Json.net to determine your program in c#
to read that json object and check is "des = true" or not.
I am using the code from MSDN documentation, to load the JSON file inside my Application Project. I wanted to use JsonObject to get the contents from the .json file.
Here is the code I am using,
Stream fs = File.Open(
#"C:\Users\AfzaalAhmad\Documents\The VS Org\Personal Diary\events.json",
FileMode.Open);
JsonObject jsonObject = (JsonObject)JsonObject.Load(fs);
But when it is executed it gives me the following error. Please note that the file is Empty.
System.FormatException
The snapshot for the error is as
In the documents I read that the .Load() method takes a Parameter of System.IO.Stream type, the code shows same return type for the fs. But when it is executed it gives me the error. What should I be doing, in order to correct this error?
The exception of System.FormatException gets thrown when there was error converting data and constructing an object.
http://msdn.microsoft.com/en-us/library/system.formatexception.aspx
In my file, the error was that the File was initially empty. Not even a single object was there, which would be a possible JSON object. So, the File content was not perfect fit for the JSON Standards. Thus the Exception got thrown.
I changed that, and used a simple, if else block to check for the contents. It was fixed this way.
Basically, I'm building a website that allows user to upload file.
From the front end (JavaScript), the user will browse a file, I can get the site to send POST data (the parameter "UploadInput" and it's value, which the value is the file)
In the backend (C#), I want to make a copy of the file and save it in a specific path.
Below is the way I did it.
var files = Request.Files;
file[0].SaveAs("\temp\\" + file[0].FileName);
The problem I ran into is that I got the error message saying index out of range. I tried Response.Write(files.Count) and it gives me 0 instead of 1.
I'm wondering where I did wrong and how to fix it, or if there's a better way of doing it.
Thanks!
Edit:
I am using HttpFox to debug. From HttpFox, I can see that under POST data, parameter is "UploadInput" and the value is "test.txt"
Edit 2:
So I tried the way Marc provides, and I have a different problem.
I am able to create a new file, however, the content is not copied over. I tried opening the new created file in notepad and all it says is "UploadInput = test.txt"
If they simply posted the file as the body content, then there will be zero "files" involved here, so file[0] will fail. Instead, you need to look at the input-stream, and simply read from that stream. For example:
using(var file = File.Create(somePath)) {
Request.InputStream.CopyTo(file);
}
I have a method that retrieves data from a json serialized string and writes it to a .json file using:
TextWriter writer = new StreamWriter("~/example.json");
writer2.Write("{\"Names\":" + new JavaScriptSerializer().Serialize(jsonData) + "}");
data(sample):
{"People":{"Quantity":"4"}, ,"info" :
[{"Name":"John","Age":"22"}, {"Name":"Jack","Age":"56"}, {"Name":"John","Age":"82"},{"Name":"Jack","Age":"95"}]
}
This works perfectly however the jsonData variable has content that is updated frequently. Instead of always deleting and creating a new example.json when the method is invoked,
Is there a way to write data only to a specific location in the file? in the above example say to the info section by appending another {"Name":"x","Age":"y"}?
My reasoning for this is I ran into an issue when trying to serialize a large amount of data using visual studio in C#. I got "The length of the string exceeds the value set on the maxJsonLength propertyā€¯ error. I tried to increase the max allowed size in the web.config using a few suggested methods in this forum but they never worked. As the file gets larger I feel I may run into the same issue again. Any other alternatives are always welcome. Thanks in advance.
I am not aware of a JSON serializer that works with chunks of JSON only. You may try using Json.NET which should work with larger data:
var data = JsonConvert.SerializeObject(new { Names = jsonData });
File.WriteAllText("example.json", data);