Using ServiceStack.Text to deserialize a json string to object

后端 未结 1 1604
清酒与你
清酒与你 2021-01-04 17:38

I have a JSON string that looks like:

\"{\\\"Id\\\":\\\"fb1d17c7298c448cb7b91ab7041e9ff6\\\",\\\"Name\\\":\\\"John\\\",\\\"DateOfBirth\\\":\\\"\\\\/Date(3174         


        
相关标签:
1条回答
  • 2021-01-04 18:26

    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();
    
    0 讨论(0)
提交回复
热议问题