I have a TextReader which reads from a JSON file, I want to convert that JSON into a XML, which I can do via following code.
public static XDocument? LoadXNode(TextReader textReader, string deserializeRootElementName)
{
var settings = new JsonSerializerSettings
{
Converters = { new XmlNodeConverter { DeserializeRootElementName = deserializeRootElementName } },
};
using var jsonReader = new JsonTextReader(textReader) { CloseInput = false };
return JsonSerializer.CreateDefault(settings).Deserialize<XDocument>(jsonReader);
}
However, I would like the method above to accept a stream writer as a parameter and write the Xml to that StreamWriter. By the way the mentioned StreamWriter is used to write to response.Body inside of a ASP .NET API. The goal of this is to load a json file and return it to the API consumer in the XML format is the most efficient way possible. That's why I want to skip the step, where I first deserialize the XML and then write it to the StreamWriter.
i am writing a script that loads an array of JSON objects from a file and check if the individual element or Json object is malformed, then it throws an error.
i want to run a loop on the array to list out the faulty json objects.
please how do i go about it.
heres my code.
//function to load the json file from the host - works perfectly..
function loadJsonFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//load the json file and parse the data.
loadJsonFile("test_data.json", function(text){
var data = JSON.parse(text);
runTestCases(data);
});
//run a test on each json object and log out the faulty ones..
//if the loop throws an error at any point it should continue to the nest node
//within the loop,and should not stop there until it has finished.
const runTestCases = (obj) => {
obj.forEach((o, v)=>{
try{
// how do test for a malformed json object
}catch(error){
throw new Error('this json object wasnt formed properly');
}
});
console.log(testShape);
}
I need to output some JSON file to client app. So, I have following code
var content = System.IO.File.ReadAllText(this.path);
var model = JsonConvert.DeserializeObject(content, new JsonSerializerSettings() {
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return Ok(model);
it should be returned as Object with camelCase property names, but I get it the same as it is in JSON file (PascalCase)
to be mentioned, in the Startup file, IMvcBuilder.AddJsonOptions also sets
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
});
and it works perfectly, other controllers returns objects as expected. The problem is only with object converted from JSON file.
How can I fix that?
Ok, I've found a way to fix it with
var model = JsonConvert.DeserializeObject<JObject>(content);
and now it works as expected :|
How do I get the binary data of the buffer in C#?
item = {[_buffer, JVBERi0xLjMKJeLjz9MKMiAwIG9iago8PAovQ3JlYXRpb25EYXR]}
I tried this but get an error:
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var dataStream = response.Content.ReadAsStringAsync().Result;
var parsed = JObject.Parse(dataStream);
if (dataStream == null)
return HttpNotFound();
foreach (dynamic item in parsed)
{
// If user decides to save the file, this will help...
Response.AddHeader("content-disposition", "filename=" + Path.GetFileName(fileDoc));
return File(item._buffer, "application/pdf");
}
}
Assuming your raw JSON looks something like this:
{
"_buffer": "JVBERi0xLjMKJeLjz9MKMiAwIG9iago8PAovQ3JlYXRpb25EYXRlIChEOjIwMTgwMTI2MjI0ODI1LTA1JzAwJykKL01vZERhdGUgKEQ6MjAxODAxMjYyMjQ4MjUtMDUnMDAnKQovUHJvZHVjZXIgKEJDTCBlYXN5UERGIDcuMDAgXCgwMzU1XCkpCi9DcmVhdG9yIChlYXN5UERGIFNESyA3IDcuMCkKPj4KZW5kb2JqCgo4"
}
Then the value of the "_buffer" property would appear to be Base64 encoded binary. As documented in its serialization guide Json.NET supports automatically deserializing Base64 strings to byte []. Thus you can do:
var _buffer = JsonConvert.DeserializeAnonymousType(dataStream, new { _buffer = (byte[])null })._buffer;
Then pass the returned byte array to Controller.File(Byte[], String).
By using JsonConvert.DeserializeAnonymousType() you avoid the need to load your (possibly large) response into an intermediate JToken hierarchy, and also avoid the need to create an explicit, concrete type just to deserialize a single byte [] property.
I have the following JSON
{
"extras": {
"google.sent_time": 1502027522898,
"custom": "{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}",
"from": "62572096498",
"alert": "Read More...",
"title": "New message",
"google.message_id": "0:2905559%2ecccafd7ecd"
}
}
Using
var jsonObj:Object = JSON.parse(str);
Gives the error:
SyntaxError: Error #1132: Invalid JSON parse input.
at JSON$/parseCore()
at JSON$/parse()
I do not understand why this is, the JSON is valid.
Additional information,
The solution I have tried and works is as follows, despite the before and after been valid.
var clean:String = str.split("\\").join('');
clean = clean.replace('"custom":"{"a"', '"custom":{"a"');
clean = clean.replace('"}","from"', '"},"from"');
Few observations :
The JSON provide in OP is looking like a JSON object instead of JSON string.Hence, No need to parse the whole object.
As partialJsonObj.extras.custom is a JSON string parse it to convert into JSON Object.
DEMO
var partialJsonObj = {
"extras": {
"google.sent_time": 1502027522898,
"custom": "{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}",
"from": "62572096498",
"alert": "Read More...",
"title": "New message",
"google.message_id": "0:2905559%2ecccafd7ecd"
}
};
partialJsonObj.extras.custom = JSON.parse(partialJsonObj.extras.custom);
var jsonObj:Object = partialJsonObj;
console.log(jsonObj);
If this "JSON" is part of your actionscript it's an Object, not a JSON.
The JSON.parse method won't work because accepts JSON-formatted String as first parameter and you pass and Object instead.
If you load/import this script from a JSON file, the JSON.parse method will work.
// importing the external JSON file
function loadJSON() {
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, decodeJSON);
loader.load(new URLRequest("test.json"));
}
// converting to actionscript Object
function decodeJSON(e:Event):void {
var loader:URLLoader = URLLoader(e.target) ;
var jsonObj:Object = JSON.parse(loader.data);
trace(jsonObj["extras"]["custom"]["a"]["message_id"]);
}
loadJSON();
If you want to access the "custom" value, uncomment double quotes in the JSON file:
"custom": {"a":{"message_data":"","message_id":"749","message_command":"MESSAGE"},"i":"899ec3dd"},
I believe str is a javascript object already, so nothing to parse and you can simply assign it like:
var jsonObj:Object = str;
However I'd assume you need to parse and convert to object your custom property:
a.extras.custom = JSON.parse("{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}")