Deserializing/Serializing in PascalCase


#1

Is there a way to serialize or deserialize so that my JSON is stored in PascalCase?

Currently it is serializing my POCO’s into camelCase?

Any examples on how to code this would be appreciated.

I am using version 2.2.4.


#2

Sure, you have a couple of options.

First, you can change the SerializerSettings and DeserializerSettings in the Couchbase SDK. However, this approach is flagged as obsolete, so I wouldn’t recommend it.

Another approach is to implement a customer ITypeSerializer that uses the serialization approach you prefer. Here’s a quicky in VB (sorry) that uses the defaults for Newtonsoft.Json, which is PascalCase.

Imports System.IO
Imports System.Text
Imports Couchbase.Core.Serialization
Imports Newtonsoft.Json

Public Class CouchbaseSerializer
    Implements ITypeSerializer

    Public Function Deserialize(Of T)(stream As Stream) As T Implements ITypeSerializer.Deserialize
        Using reader As New StreamReader(stream)
            Return JsonConvert.DeserializeObject(Of T)(reader.ReadToEnd())
        End Using
    End Function

    Public Function Deserialize(Of T)(buffer() As Byte, offset As Integer, length As Integer) As T Implements ITypeSerializer.Deserialize
        Return JsonConvert.DeserializeObject(Of T)(Encoding.UTF8.GetString(buffer, offset, length))
    End Function

    Public Function Serialize(obj As Object) As Byte() Implements ITypeSerializer.Serialize
        Return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj))
    End Function

End Class

#3

@btburnett3 Thanks for the quick reply.

Forgive my ignorance. How do I actually use CouchbaseSerializer class?


#4

@ibrahim.hadad -

Alternatively you can still change the deserialization settings if you manually create DefaultSerializer and pass in the JsonSerializerSettings and JsonDeserializerSettings in the ctor. Something like this:

var config = new ClientConfiguration();
config.Serializer = ()=>new DefaultSerializer(new JsonSerializerSettings(), new JsonSerializerSettings());
var cluster = new Cluster(config);

This will default back to Pascal I believe. This also answers your question regarding how to use CouchbaseSerializer above.

-Jeff


#5

Thanks @jmorris! That worked.

To future readers of this post make sure you include the following using statements:

using Couchbase.Core.Serialization;
using Newtonsoft.Json;