Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ServiceStack.Text to deserialize a json string to object

I have a JSON string that looks like:

"{\"Id\":\"fb1d17c7298c448cb7b91ab7041e9ff6\",\"Name\":\"John\",\"DateOfBirth\":\"\\/Date(317433600000-0000)\\/\"}"

I'm trying to deserialize it to object (I'm implementing a caching interface)

The trouble I'm having is when I use

JsonSerializer.DeserializeFromString<object>(jsonString);

It's coming back as

"{Id:6ed7a388b1ac4b528f565f4edf09ba2a,Name:John,DateOfBirth:/Date(317433600000-0000)/}"

Is that right?

I can't assert on anything... I also can't use the dynamic keyword....

Is there a way to return an anonymous object from the ServiceStack.Text library?

like image 631
Alex Avatar asked Feb 06 '14 10:02

Alex


1 Answers

Using the JS Utils in ServiceStack.Common is the preferred way to deserialize adhoc JSON with unknown types since it will return the relevant C# object based on the JSON payload, e.g deserializing an object with:

var obj = JSON.parse("{\"Id\":\"..\"}");

Will return a loose-typed Dictionary<string,object> which you can cast to access the JSON object dynamic contents:

if (obj is Dictionary<string,object> dict) {
    var id = (string)dict["Id"];
}

But if you prefer to use ServiceStack.Text typed JSON serializers, it can't deserialize into an object since it doesn't know what type to deserialize into so it leaves it as a string which is an object.

Consider using ServiceStack's dynamic APIs to deserialize arbitrary JSON, e.g:

var json = @"{\"Id\":\"fb1d17c7298c448cb7b91ab7041e9ff6\",
          \"Name\":\"John\",\"DateOfBirth\":\"\\/Date(317433600000-0000)\\/\"}";

var obj = JsonObject.Parse(json);
obj.Get<Guid>("Id").ToString().Print();
obj.Get<string>("Name").Print();
obj.Get<DateTime>("DateOfBirth").ToLongDateString().Print();

Or parsing into a dynamic:

dynamic dyn = DynamicJson.Deserialize(json);
string id = dyn.Id;
string name = dyn.Name;
string dob = dyn.DateOfBirth;
"DynamicJson: {0}, {1}, {2}".Print(id, name, dob);

Another option is to tell ServiceStack to convert object types to a Dictionary, e.g:

JsConfig.ConvertObjectTypesIntoStringDictionary = true;
var map = (Dictionary<string, object>)json.FromJson<object>();
map.PrintDump();
like image 114
mythz Avatar answered Nov 10 '22 12:11

mythz