Kyle Gobel - 12 - Mar 20, 2015

I’m wondering how to handle this serialization case.

I have some dynamic json that sometimes contains very long numbers.

Like so:

{ “unique_identifier” : “06166814539169448873926924040237” }

Which is fine except I need to modify/add to this json, so I do something like this

var json = JsonObject.Parse(myJsonString);
//do modifications here
var newJson = json.ToJson();

When I cast this back to json, the string will look like

//newJson.Print()
{ “unique_identifier” : 06166814539169448873926924040237 }

(it recognizes unique_identifier as a number, and serializes it as such, except in any parser i can find, this is not valid json).

Anyone know an easy work around to get this still serialize as if it were a string?

JsonObject tries to infer the JSON type by inspecting the string value. You can use your own class for this instead, e.g:

public class MyId {
    public string unique_identifier { get; set; }
}

var obj = json.FromJson<MyId>();
obj.unique_identifier = “”; //modify
var modifiedJson = obj.ToJson(); //serialize

Kyle Gobel:

In the real world I won’t know what keys this contains, in my scenario I need to take whatever json is given to me, and simply add/modify a key, and then pass it down the pipe.

Is there another solution you know off the top of your head?

Also…wouldn’t it be better to change the logic of detecting if it’s a number or string to always use string if the value length is greater than x?  I don’t know the json ‘spec’, but it seems everywhere i look, having a 40 digit number is not  valid json.

md5ing and empty guids from other languages (that don’t have a - (dash) by default) are causing issues very rarely when they don’t have a letter in them.

I’ve just added a range check for this which should resolve the number inference: https://github.com/ServiceStack/ServiceStack.Text/commit/85b0a85ae332af9a15a4769a3019185f25a351ee

Still in the middle of something else right now, but will let you know when the next version is deployed to MyGet.

FYI change is now deployed to MyGet: https://github.com/ServiceStack/ServiceStack/wiki/MyGet

Kyle Gobel:

Awesome, thanks Demis!