Using ServiceStack.Text to deserialize a json string to object
Asked Answered
C

1

10

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?

Chayachayote answered 6/2, 2014 at 10:59 Comment(0)
O
20

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();
Onomasiology answered 6/2, 2014 at 13:9 Comment(3)
Looks good... when I do this, the "properties" of my object come back (for example) as : [0] {[Name, John]} - an array of key / value... is that right?Chayachayote
I wanted to try ServiceStack's dynamic API but for me there isn't .Get<T>(key) method of JsonObject. I only installed "Install-Package ServiceStack.Text". Can you advice what I may be missing?Grew
@Grew .Get<T> is an instance extension method, please go through the linked json parsing examples on the home page.Onomasiology

© 2022 - 2024 — McMap. All rights reserved.