json.net serialization/deserialization on an external json file - c#
I'm working with c# within VS2012 and have installed the json.net files to handle the deserialization of a json string that's stored in an external file (1.json). As a newbie, i've come across a situation in which I want to extract information called score and avarage score from a single json string; see below:
{"LEVEL": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
"score": 1,
"average score": 2 }
The output I get from the debugger once I step through the process shows that the stream only picks up the first part of the json file (everything from the first opening square bracket to the closing square bracket) so I'm unable to obtain the score and average score. Here is what I have at the moment to try to extract this information...
using (var sr = new StreamReader(File.OpenRead(filename)))
{
levelData = sr.ReadLine();
var stats = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(levelData);
}
Can anyone provide any advice as to how I can extract this information? Any help would be greatly appreciated.
The problem is that you're reading and the file and deserializing data line by line. You cannot do that with json as it is the whole structure (like xml).
Instead you should deserialize the whole file:
var json = File.ReadAllText(filename);
var stats = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);
Related
Xamarin Forms: How to Read Data from Json File from the Phonestorage of my android smartphone
im trying to read Data From A Json File that is in the Storage of the Phone that uses the App. How can I Do that ?
This is how I would do it. Additional information can be found in File Handling in Xamarin.Forms: // get file name string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YourJsonFile.json"); // read file string json = File.ReadAllText(fileName); // deserialize/parse json var data = JsonConvert.DeserializeObject<Data>(json); // or var jObject = JObject.Parse(json); The above assumes use of Newtonsoft.Json, however, similar can be achieved using System.Text.Json.
Is any ways to convert google protobuf message into json with indentation?
I need to save Google protobuf IMessage object into json file, using C#. here is sample code: using (var input = File.OpenRead(protodatFile)) { string jsonString = null; message.MergeFrom(input); //read message from protodat file JsonFormatter formater = new JsonFormatter( new JsonFormatter.Settings(false)); jsonString = formatter.Format(message); System.IO.File.WriteAllText(jsonFile, jsonString); } This uses the JsonFormatter from the Google Protobuf library. The problem: all json content is stored in one line. when file is quite big(>50 MB) it is hard to open/view in text editor. What is the best way to make indented jsonFile here?
As an extremely inefficient workaround, one can use Json.NET to re-format the Protobuffer Json: // Re-Parse the one-line protobuf json string into an object: object parsed = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString); // Format this object as JSON with indentation: string jsonWithIndent = Newtonsoft.Json.JsonConvert.SerializeObject(parsed, Newtonsoft.Json.Formatting.Indented); Since the original question asked about a 50MB file, this is probably a bad solution for such large-ish files, but given that I couldn't find anything on JsonFormatter.Settings, it was what I reached for.
As of version 3.22.0 of Google.Protobuf you can use the following: JsonFormatter formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithIndentation()); output = formatter.Format(msg); See here for the corresponding issue: https://github.com/protocolbuffers/protobuf/pull/9391
How can i save the Body data collected from Kinect 2.0 and save it in a JSON file?
I am using lightbuzz library for my project. I am trying to get the data from "BodyWrapper _captureBody" and save iy in a file. The content of "_captureBody" is here... I tried to serialize the object and then i tried to copy the content in the .Json file but here is the error i got.It says I cannot Serialize or desalinize it. Here is the small part of code : if (_mode == ViewMode.Capture && _currentBody != null) { _capturedBody = _currentBody.ToBodyWrapper(); //capture the data of the current body coming from kinect. if (i < 1) { capturebody[i] = _capturedBody; i++; } if (i == 1) //i want to save the data only once { string json = new JavaScriptSerializer().Serialize(_capturedBody); //write string to file System.IO.File.WriteAllText(#"C:\path.json", json); } } You can use this link "https://vitruviuskinect.com/documentation/windows/html/e07dd042-e9f1-c9b8-2e94-c20576115f3d.htm" for reference
Joints is a Dictionary with key JointType. As you can see in the exception, the keys need to be string or object. I think it's better if you make your own class system (with constructor with the body as argument) and then make sure it's serializable. This means that you'll need to change that property. From own experience I try to stay away from dictionaries and JSON. Maybe convert it to a class with a Custom Joint class that has an extra property with the enum.
I have solved this issue myself now. here is what i did, I used the method ToJSON to serialize a Kinect Body object. string json = body.ToJSON(); //The body contains all the Kinect generated data. Then I saved the file using: File.SaveAllText(json, "path-of-file.json"); if the above Syntax doesn't work then you can also use to save .json file: File.WriteAllText(path-of-file,json); And finally to read the JSON file again I used : BodyWrapper body = File.ReadAllText("path-of-file.json").ToBodyWrapper(); Thanks for the help anyway... :-)
Big Data Xml file (file size over 20GB) convert to Json File
I have an XML file. I want to convert it to JSON with C#. However, the XML file is over 20 GB. I have tried to read XML with XmlReader, then append every node to a JSON file. I wrote the following code: var path = #"c:\result.json"; TextWriter tw = new StreamWriter(path, true, Encoding.UTF8); tw.Write("{\"A\":"); using (XmlTextReader xmlTextReader = new XmlTextReader("c:\\muslum.xml")) { while (xmlTextReader.Read()) { if (xmlTextReader.Name == "A") { var xmlDoc = new XmlDocument(); var v = xmlTextReader.ReadInnerXml(); string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.None, true); tw.Write(json); } } } tw.Write("}"); tw.Close(); This code not working. I am getting error while converting json. Is there any best way to perform the conversion?
I would do it the following way generate classes out of xsd schema using xsd.exe open file and read top level ( i e your document level ) tags one by one (with XmlTextReader or XmlReader) serialize each tag into object using generated classes deserialize resulting object to json and save to whatever consider saving in batches of 1000-2000 tags you are right about serialize/deserialize being slow. still doing work in several threads, preferably using TPL will give you good speed. Also consider using json.net serializer, it is really a lot faster than standard ones ( it is standard for web.api though) I can put some code snippets in the morning if you need them. We are processing big ( 1-10gigs) files this manner in order to save data to sql server database.
write to specific position in .json file + serilaize size limit issue C#
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);