How to force Newtonsoft.Json.Net Dictionary to serialize as KeyValuePair - json.net

Is it possible to get Json.Net 4.5+ to serialize my Dictionary<,> as this;
{
dic:[
{k:"apples",v:2},
{k:"pears",v:43}
]
}
as opposed to;
{
dic:{
"apples":2,
"pears":43,
}
}
Whilst the latter is a great default, and looking at the SO posts almost everyone wanted this when it wasn't the default, but I have one specific case when I actually want it the other (former) way instead. I tried adding the following to the dictionary class or member;
[JsonProperty(ItemConverterType=typeof(DictionaryArrayConverter)]
But that just causes it to barf on a null in the serialization stack.

Related

CamelCase property names with NJsonSchema C# CodeGeneration

does anybody know a way to configure NJsonSchema to use CamelCase property naming durching code generation? I've a JSON schema with property names like message_id which lead to C# property name 'Message_id' where i.e. 'MessageId' whould be a more C#-like way.
With an attribute like '[JsonProperty("message_id"]' it would be no problem to specified the connection between the different names.
So, you asked about code generation. I was having trouble with the schema it generated not matching what was getting sent to my Angular app. So, while this isn't exactly what you were looking for, perhaps it helps you find an answer (maybe?).
To generate the schema with the camel case property names, I'm setting the Default Property Name Handling to CamelCase, but this is using the deprecated call to set these settings directly. There should be some way to use the SerializerSettings directly, but I wasn't quite able to make that work. This isn't production code for me, so it will do.
internal class SchemaFileBuilder<T>
{
public static void CreateSchemaFile()
{
CreateSchemaFile(typeof(T).Name);
}
public static void CreateSchemaFile(string fileName)
{
JsonSchemaGeneratorSettings settings = new JsonSchemaGeneratorSettings();
settings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
var schema = NJsonSchema.JsonSchema.FromType<T>(settings);
var json = schema.ToJson();
Directory.CreateDirectory("Schemas");
File.WriteAllText($"Schemas\\{fileName}.schema.json", json);
}
}
I set this up as a generic function so I could pass multiple schemas in to either createSchemaFile functions. Here's are some example calls which would generate a Person.schema.json file and a Persons.schema.json file:
SchemaFileBuilder<Person>.CreateSchemaFile();
SchemaFileBuilder<Dictionary<string, Person>>.CreateSchemaFile("Persons");

Kotlin Reflection - Check if property has type

I want to iterate over all fields in one of my classes, filter for annotated ones and then check if the field has one specific type.
All I found was field.returnType.isSubtype(other: KType) but I don't know how to get the KType of my other class.
Here is my code so far:
target.declaredMemberProperties.forEach {
if (it.findAnnotation<FromOwner>() != null) {
if ( /* it.returnType is Component <- Here I need some working check */ ) {
// do stuff
} else {
// do ther stuff
}
}
}
There are at least two solutions here:
Get the KClass<*> of it.returnType using .jvmErasure, then check the subtype relationship for the KClasses:
it.returnType.jvmErasure.isSubclassOf(Component::class)
Since Kotlin 1.1, you can construct the KType from the KClass token using .createType() (check its optional parameters: you can use them to provide nullability info, type arguments and annotations), and then check the subtype as you suggested:
it.returnType.isSubtypeOf(Component::class.createType())
Creating the type on every iteration may introduce performance issues, make sure you cache it if you need it often.

strongly typed sessions in asp.net

Pardon me if this question has already been asked. HttpContext.Current.Session["key"] returns an object and we would have to cast it to that particular Type before we could use it. I was looking at various implementations of typed sessions
http://www.codeproject.com/KB/aspnet/typedsessionstate.aspx
http://weblogs.asp.net/cstewart/archive/2008/01/09/strongly-typed-session-in-asp-net.aspx
http://geekswithblogs.net/dlussier/archive/2007/12/24/117961.aspx
and I felt that we needed to add some more code (correct me if I was wrong) to the SessionManager if we wanted to add a new Type of object into session, either as a method or as a separate wrapper. I thought we could use generics
public static class SessionManager<T> where T:class
{
public void SetSession(string key,object objToStore)
{
HttpContext.Current.Session[key] = objToStore;
}
public T GetSession(string key)
{
return HttpContext.Current.Session[key] as T;
}
}
Is there any inherent advantage in
using
SessionManager<ClassType>.GetSession("sessionString")
than using
HttpContext.Current.Session["sessionString"] as ClassType
I was also thinking it would be nice
to have something like
SessionManager["sessionString"] = objToStoreInSession,
but found that a static class cannot have an indexer. Is there any other way to achieve this ?
My thought was create a SessionObject which would store the Type and the object, then add this object to Session (using a SessionManager), with the key. When retrieving, cast all objects to SessionObject ,get the type (say t) and the Object (say obj) and cast obj as t and return it.
public class SessionObject { public Type type {get;set;} public Object obj{get;set;} }
this would not work as well (as the return signature would be the same, but the return types will be different).
Is there any other elegant way of saving/retrieving objects in session in a more type safe way
For a very clean, maintainable, and slick way of dealing with Session, look at this post. You'll be surprised how simple it can be.
A downside of the technique is that consuming code needs to be aware of what keys to use for storage and retrieval. This can be error prone, as the key needs to be exactly correct, or else you risk storing in the wrong place, or getting a null value back.
I actually use the strong-typed variation, since I know what I need to have in the session, and can thus set up the wrapping class to suit. I've rather have the extra code in the session class, and not have to worry about the key strings anywhere else.
You can simply use a singleton pattern for your session object. That way you can model your entire session from a single composite structure object. This post refers to what I'm talking about and discusses the Session object as a weakly typed object: http://allthingscs.blogspot.com/2011/03/documenting-software-architectural.html
Actually, if you were looking to type objects, place the type at the method level like:
public T GetValue<T>(string sessionKey)
{
}
Class level is more if you have the same object in session, but session can expand to multiple types. I don't know that I would worry about controlling the session; I would just let it do what it's done for a while, and simply provide a means to extract and save information in a more strongly-typed fashion (at least to the consumer).
Yes, indexes wouldn't work; you could create it as an instance instead, and make it static by:
public class SessionManager
{
private static SessionManager _instance = null;
public static SessionManager Create()
{
if (_instance != null)
return _instance;
//Should use a lock when creating the instance
//create object for _instance
return _instance;
}
public object this[string key] { get { .. } }
}
And so this is the static factory implementation, but it also maintains a single point of contact via a static reference to the session manager class internally. Each method in sessionmanager could wrap the existing ASP.NET session, or use your own internal storage.
I posted a solution on the StackOverflow question is it a good idea to create an enum for the key names of session values?
I think it is really slick and contains very little code to make it happen. It needs .NET 4.5 to be the slickest, but is still possible with older versions.
It allows:
int myInt = SessionVars.MyInt;
SessionVars.MyInt = 3;
to work exactly like:
int myInt = (int)Session["MyInt"];
Session["MyInt"] = 3;

Refactoring With Reflection

I have several methods that populate a SQLCommand objects parameter collection from an object like this
if (!String.IsNullOrEmpty(SearchObj.FirstName))
{
command.AddParameter(Fields.FirstName, SearchObj.FirstName);
}
if (!String.IsNullOrEmpty(SearchObj.LastName))
{
command.AddParameter(Fields.LastName, SearchObj.LastName);
}
if (!String.IsNullOrEmpty(SearchObj.EmailAddress))
{
command.AddParameter(Fields.EmailAddress, SearchObj.EmailAddress);
}
if (SearchObj.JobRoleId > -1)
{
command.AddParameter(Fields.JobRoleId, SearchObj.JobRoleId);
}
This can get messy as the object can have up to about 20 properties. Is there anyway using reflection to loop through each of these properties and add them all to the Sqlcommand objects Parameter collection? Bearing in mind it treats strings different to ints in that it only adds a string if its not null or empty and it only adds an int if its greater than -1.
I've not used much reflection before, so a point in the right direction would be great.
Thanks
Try using the methods listed here:
How to get the list of properties of a class?
and then loop over them adding them as you see fit.

modifying a value in viewstate

Say I have a property like...
public object MyObject
{
get { return (object)ViewState["myobject"]; }
set { ViewState["myobject"] = value; }
}
I modify the object like so...
object myObjCopy = MyObject;
myObjCopy.ChangeSomething();
MyObject = myObjCopy;
Is this the correct method? It just feels really clunky and I wonder if I'm missing something. Is there some clever paradigm which enables modifying viewstate more intuitively without using temporary copys everywhere in my code.
With the property you have defined, you should not need to do any copying like what you have. I'm not sure what ChangeSomething() does, but you should be able to call it directly on the property. I would normally not pull it out as an object... It's been a while since I did pure webforms development, but my ViewState helper properties usually looked more like:
public string CurrentUsername
{
get
{
if (ViewState["Username"] is string)
return (string)ViewState["Username"];
return null;
}
set { ViewState["Username"] = value; }
}
Edit: Thinking about it, I guess the copy is probably there just to remove the potential performance overhead of casting every time you reference the property. I don't think this is a valid optimization in most cases, but if you feel strongly about it, you could hide it with something like this:
private string m_CurrentUsername;
public string CurrentUsername
{
get
{
if (m_CurrentUsername == null && ViewState["Username"] is string)
m_CurrentUsername = (string)ViewState["Username"];
return m_CurrentUsername;
}
set { ViewState["Username"] = m_CurrentUsername = value; }
}
Like I said though - I wouldn't recommend this.
The correct answer is that you shouldn't be modifying viewstate at all. Your controller should create the models and populate the viewstate only just before returning the view. If you're writing this code in the view, you've got an even bigger problem. in general, the view should contain little (if any) code that changes or does things.
Edit: Oops, I think I just got ViewData (in asp.net mvc) confused with viewdata. sorry ... to answer your real question, yes, that is just about the only way :-) it's not really clunky when you are dealing with a "bag" API like the viewstate is.

Resources