简体   繁体   中英

JSon Deserializing getting type

class Program
{
    static void Main(string[] args)
    {
        string json = JsonConvert.SerializeObject(new Account { Name = "test" }, Newtonsoft.Json.Formatting.Indented,
        new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, PreserveReferencesHandling = PreserveReferencesHandling.Objects });
        Console.Out.Write(json);
        while (true) 
        {
        }
    }
}

class Account {
    public String Name;
}

Hey, im trying to get into Json. I want to deserialize an object. I want to get the type information out of the string. So when i deserialize i want json to recognize the type by itself without specifying it. Is that possible?

Best Regards, Brian

Json.net unfortunately can't infer the type by the json, but if you would like to operate on Json objects dynamically, check out the JToken, JObject, and JArray types from the Newtonsoft.Json.Linq namespace. You can read Json from a path like so

var myObject = JObject.Parse(jsonString)
var someObject = myObject["myOtherObject"]["otherThing"];
var myString = (string) someObject["theString"];

I find this part of Json.net very useful and I hope it helps you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM