map json schema to c# model with NJsonSchema throws System.InvalidCastException - c#

Im trying to convert really simple json schema to my c# model using nuget from this link
Im using example code from the github repo such as:
var schema = """{"$schema":"http://json-schema.org/draft-04/schema#","title":"Person","type":"object","additionalProperties":false,"required":["FirstName","LastName"],"properties":{"FirstName":{"type":"string"},"LastName":{"type":"string"}},"definitions":{}}""";
var generator = new CSharpGenerator(schema);
var file = generator.GenerateFile("mytest"); // on this line I got an exception
Console.WriteLine(file);
Console.ReadLine();
this is my json schema:
Notice: Im using .net 7 , you can notice that Im using tripple string in order to accept json with double quotes.
Exception that I get:
System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'NJsonSchema.JsonSchema'.'
What I did wrong here?

Related

Json with C# and Mono

I'm trying to read a json string into memory and get this undocumented error msg
$ mcs -r:FortnoxAPILibrary.dll -r:npgsql.dll -r:System.Data.dll -r:Newtonsoft.Json.dll Vouchers.cs
Vouchers.cs(44,18): error CS0103: The name `JArray' does not exist in the current context
Compilation failed: 1 error(s), 0 warnings
My code is
var json = System.IO.File.ReadAllText("test.json");
var objects = JArray.Parse(json); // parse as array
foreach(JObject root in objects)
{
foreach(KeyValuePair<String, JToken> app in root)
{
var appName = app.Key;
var description = (String)app.Value["Description"];
var value = (String)app.Value["Value"];
Console.WriteLine(appName);
Console.WriteLine(description);
Console.WriteLine(value);
Console.WriteLine("\n");
}
}
Where is it documented how this should work?
You are more than likely missing a using statement.
using Newtonsoft.Json.Linq;
Every piece of C# code you write, except for core types, requires a using statement pointing to any dependencies.
C# libraries often don't document the using statement requirements for a block of code. Maybe an oversight, but most users are using an IDE, which warns of the missing statement and offers options to automatically insert them.
It is not documented that I must include this line.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Reading JSON data throws runtime exception

According to NewtonSoft's documentation, this code:
string props = "{\"lot\":\"TEST\",\"mhd\":\"2016-06-17\"}";
dynamic json = JsonConvert.DeserializeObject(props);
string s = json.mhd;
should work, but I get a RunTimeBinderException when I try it. I have Micrsoft.CSharp referenced and the compile works (it is a runtime error). I am compiling against .NET 4.0, using NewtonSoft version 7.
I tried accessing as json["mhd"], which works fine.
Am I missing something?
The json object is a JObject, so to get the value you need do:
string s = (string)json["mhd"];
I try this case in Newtonsoft.Json 3.5.8 version ,I get this error.
When I upgrade Newtonsoft.Json package version to 4.5.1 it works .
I think it has bug on older version.
#Candide pointed out what was wrong with your example, but if you still want to use json.mhd syntax and have real dynamic object to work with you can do it.
Try to deserialize it using the ExpandoObjectConverter:
var converter = new ExpandoObjectConverter();
dynamic json = JsonConvert.DeserializeObject<ExpandoObject>(props, converter);

Error while XML deserialization to class generated by XSD tool

I want to integrate UPS service Locator.
I download from UPS website two XSD templates describing request and response. To generate c# classes I used XSD.exe tool. It generated two files for each template. In both classes are duplicated classes, which make errors, so I remove duplicated classes from one file.
Everything works, I obtain data from UPS API, but when I try to deserialize response to object LocatorResponse (class generated from XSD template) I get errors
Unable to generate a temporary class (result=1). error CS0030: Cannot
convert type 'string[]' to 'string' error CS0029: Cannot implicitly
convert type 'string' to 'string[]'
My code, I attach also generated class
string authBody = GetAuthString();
string accessPoint = GetAccessPointPostBody();
var response = GetResponseString(authBody + accessPoint);
using (TextReader reader = new StringReader(response))
{
// this line below makes problem
var serializer = new XmlSerializer(typeof(LocatorResponse));
// this line above makes problem
var result = (LocatorResponse)serializer.Deserialize(reader);
}
What I do wrong??

Databinding XML in C# (WP8)

I'm not sure if this is correct, but trying to learn MVVM, how it works, etc.
Currently, the example used to load the data is:
this.SavedItems.Add(new SavedBoard() { ID= "1098", UserDescription = "Test" });
I want to parse XML and load data from there.
This is the c# code I've been trying but doesn't seem to work:
XDocument doc = XDocument.Load("savedstops.xml");
var data = from query in doc.Descendants("Stops")
select new SavedBoard
{
ID = query.Element("ID").Value,
UserDescription = query.Element("UserDescription").Value
};
this.SavedItems.Add(data);
And this is the XML file:
<Stops>
<Stop>
<ID>1022</ID>
<UserDescription>Test</UserDescription>
</Stop>
<Stop>
<ID>1053</ID>
<UserDescription>Test1045</UserDescription>
</Stop>
</Stops>
Where am I going wrong? I also get an error Error "Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable'. 'Select' not found. Are you missing a reference or a using directive for 'System.Linq'?"
Though I'm thinking the error isn't the reason it's not working, but rather the code logic itself.
Thanks in advance!
Use doc.Descendants("Stop") (or doc.Root.Elements("Stop")) instead of Stops, and include the System.Linq namespace with adding: using System.Linq; top of your code.

Cannot access Take() on a List<object> with System.Linq referenced in using

I am using RazorEngine for email templating. I have introduced Take() method into the template. I did this so the authors can dictate how many records they want without us having to change any C# in our code directly. I have tried adding the using statements to the template itself as well as using the fluent configuration and adding the namespaces needed but I am not having any luck.
Error:
'System.Collections.Generic.List<object>' does not contain a definition for 'Take'
Here is my fluent configuration for RazorEngine:
var config = new FluentTemplateServiceConfiguration(c =>
c.IncludeNamespaces(
"System",
"System.Linq",
"System.Collections",
"System.Collections.Generic"));
using (var service = new TemplateService(config))
{
//Razor.SetTemplateService(service);
dynamic dyModel = model;
var parsed = string.IsNullOrEmpty(cacheName)
? service.Parse(template, dyModel,null, cacheName)
: service.Parse(template, dyModel,null,null);
return parsed;
}
If I purposely state a namespace incorrectly, I do get an error saying it couldn't find it so I know that it is processing the config data but despite that, I am still getting the error.
Any ideas on what I am doing wrong? I am passing in a dynamic model which either is a List or has a List on it.
So this was kinda lame, there is a ticket on RazorEngine's wiki that states this was fixed, so either I am using it wrong or it hasn't been fixed but this is what I had to do to get it working in the razor file.
var topFive = ((List<dynamic>) Model.MyList).Take(5);

Categories

Resources