I am evaluating Json.Net.Schema from NewtonSoft and NJsonSchema from GitHub and I cannot figure out how to create a JSON schema from a JSON object. I want it to work exactly like this site does: http://jsonschema.net/#/
What I am looking for
string json = #"{""Name"": ""Bill"",""Age"": 51,""IsTall"": true}";
var jsonSchemaRepresentation = GetSchemaFromJsonObject(json);
I would expect a valid JSON schema in the jsonSchemaRepresentation variable. Does anyone know how I can accomplish this?
Thanks in advance!
The current version of NJsonSchema supports this feature:
The SampleJsonSchemaGenerator generates a JSON Schema from sample JSON data.
var schema = JsonSchema4.FromSampleJson("...");
var schemaJson = schema.ToJson();
... or create a SampleJsonSchemaGenerator instance and call the Generate("...") method.
Actually both of the libraries you mentioned do not support such a functionality.
If you're down to implement it yourself then you will have to parse your JSON, iterate over it recursively and add a new schema depending on the type of what you've just iterated over.
There are also some other tools (in other languages like python) which could be an inspiration, this might get you started.
The string you are submitting to the function is not in the correct format. Try this (add '{' to the start of the string, '}' to the end):
string json = #"{
""Name"": ""Bill"",
""Age"": 51,
""IsTall"": true
}";
var jsonSchemaRepresentation = GetSchemaFromJsonObject(json);
Related
I want to access a nested value with JSON.NET. I know I can use the .SelectToken() method to access a nested value (see for example this question or this question). My issue is that the JSON I'm trying to access has keys with dots in them:
var json = #"
{
""data.dot"": {
""value"": 5,
}
}";
var jo = JObject.Parse(json);
Console.WriteLine(jo.SelectToken("data.dot.value")); // <-- doesn't work
I found the answer while writing this question, so I might as well share my findings.
It turns out that the .SelectToken method is very powerful, and:
allows you to query a JSON with escaped properties by surrounding your key with ['{key}']
allows you to use regex
allows you to filter by path value
allows you to query by complex path
So in my case, I could write:
jo.SelectToken("['data.dot'].value"); // escaped property
jo.SelectToken("$..value"); // complex JSON path
I could also use the JToken indexer, but contrary to the .SelectToken method, it would throw an exception if the JSON doesn't contain the data.dot key:
jo["data.dot"]["value"]
The JSON I'm getting back from a webservice has an integer incorrectly represented as 0.0. My deserialization code looks like this:
var serializer = new JsonSerializer();
var ret = serializer.Deserialize<T>(jsonTextReader);
And I get an error like this:
Input string '0.0' is not a valid integer.
My question is, is there a way to specify a less strict deserialization method so that I can parse this string?
EDIT: The web service returns no schema so I don't know why the deserializer tries to convert it to an int instead of a float or double.
I'd say that you should go ahead and creat your classes on Json -> C#
var o = (JObject)serializer.Deserialize(myjsondata);
You can use the C# dynamic type to make things easier. This technique also makes re-factoring simpler as it does not rely on magic-strings. Use JsonConvert.DeserializeObject<dynamic>()to deserialize this string into a dynamic type then simply access its properties in the usual way in C#.
Im not sure why youre getting
Input string '0.0' is not a valid integer.
since if you dont have any Json data it should just be left at null and you shouldnt have this problem
I am attempting to convert XML into JSON in order to generate a HTTP POST request to an API. I am getting an error because one of the fields is meant to be an integer instead of a string. From what i have read adding "json:Integer="true"" to the node will cause it to become an int, but this doesnt seem to be working for me. Here is the xml and the resulting json. The arrays are working, but the integer is not.
<shipments json:Array="true" xmlns:json="http://james.newtonking.com/projects/json">
<shipment_tracking_number />
<response_shipment_date>2016-10-18T01:00:00.0000000-04:00</response_shipment_date>
<response_shipment_method>UPS Ground</response_shipment_method>
<expected_delivery_date>2016-10-18T01:00:00.0000000-04:00</expected_delivery_date>
<ship_from_zip_code>12345</ship_from_zip_code>
<carrier_pick_up_date>2016-10-18T01:00:00.0000000-04:00</carrier_pick_up_date>
<carrier>UPS</carrier>
<shipment_items json:Array="true">
<shipment_item_id>FF12345K</shipment_item_id>
<alt_shipment_item_id>1234567890</alt_shipment_item_id>
<merchant_sku>B00xxxx</merchant_sku>
<response_shipment_sku_quantity json:Integer="true">1</response_shipment_sku_quantity>
</shipment_items>
</shipments>
string jsonrequest = JsonConvert.SerializeXmlNode(doc,
Newtonsoft.Json.Formatting.None, true);
{"shipments":[
{
"shipment_tracking_number":null,
"response_shipment_date":"2016-10-18T01:00:00.0000000-04:00",
"response_shipment_method":"UPS Ground",
"expected_delivery_date":"2016-10-18T01:00:00.0000000-04:00",
"ship_from_zip_code":"12345",
"carrier_pick_up_date":"2016-10-18T01:00:00.0000000-04:00",
"carrier":"UPS",
"shipment_items":[
{
"shipment_item_id":"FF12345K",
"alt_shipment_item_id":"1234567890",
"merchant_sku":"B00xxxx",
"response_shipment_sku_quantity":"1"
}]
}]
}
I need "response_shipment_sku_quantity":"1" to show up as "response_shipment_sku_quantity":1, but it doesnt seem to be working. I can modify the XML or the code that performs the conversion. I dont mind which as long as this can be done.
You define the attribute wrongly. This is how it should look like.
<response_shipment_sku_quantity json:Type='Integer'>1</response_shipment_sku_quantity>
EDIT:
Newtonsoft.Json XmlNodeConverter
Look methods private void SerializeNode and string dataType = GetDataType(node); they suggest this definition.
Another option is to Deserialize the xml to class with proper types for the properties and after that Serialize it to Json.
Deserialize JSON into C# dynamic object?
Following above question, I copy the dynamicJsonDeserilization and trying to use that in my application.
then I try to access the object as
var Data = json.deserilization(jsonstring);
Now, my string is
{"0":{"Name":"C:\\","Type":"Partition","Path":"C:\\"},"1":{"Name":"D:\\","Type":"Partition","Path":"D:\\"},"2":{"Name":"E:\\","Type":"Partition","Path":"E:\\"}}
i.e. I just have an Array on my server which I convert to JSON string and send.
As per code from best answer I should be able to access it as Data.0 but it give "End of Expression expected", Also Data[0] is giving same error. I am not sure how can I use it ? Any help is appreciated. Thanks.
Now, my string is
{"0":{"Name":"C:\","Type":"Partition","Path":"C:\"},"1":{"Name":"D:\","Type":"Partition","Path":"D:\"},"2":{"Name":"E:\","Type":"Partition","Path":"E:\"}}
Your string is indeed not valid JSON due to escaped quotes.
Those C:\ are breaking the parser. You should generate it like this, sending three backslahes:
{"0":{"Name":"C:\\\","Type":"Partition","Path":"C:\\\"} ...
Hi I'm making a web api client that returns stuff in json.
I'm using Restsharp that uses newtonsoft.json to deserialize json objects.
The problem is that the server returns an object with a property with #Text as name. Is there a way to make restsharp parse this?
Here is a sample:
image: [
{
#text: http://userserve-ak.last.fm/serve/34s/55125087.png
size: small
}]
All the other properties are being parsed just right the only problem is this one, the property is a string type so no problem in here.
Regards
That JSON isn't valid; you need to put quotes around the #text key (so make it "#text") as well as both values (so "http://...png" and "small").