Converting a JToken (or string) to a given Type

前端 未结 4 1119
予麋鹿
予麋鹿 2020-12-08 09:00

TL;DR Version

I have a object of type JToken (but can also be a string) and I need to convert it into a Type contained in

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 09:34

    System.Convert.ChangeType(jtoken.ToString(), targetType);
    

    or

    JsonConvert.DeserializeObject(jtoken.ToString(), targetType);
    

    --EDIT--

    Uzair, Here is a complete example just to show you they work

    string json = @"{
            ""id"" : 77239923,
            ""username"" : ""UzEE"",
            ""email"" : ""uzee@email.net"",
            ""name"" : ""Uzair Sajid"",
            ""twitter_screen_name"" : ""UzEE"",
            ""join_date"" : ""2012-08-13T05:30:23Z05+00"",
            ""timezone"" : 5.5,
            ""access_token"" : {
                ""token"" : ""nkjanIUI8983nkSj)*#)(kjb@K"",
                ""scope"" : [ ""read"", ""write"", ""bake pies"" ],
                ""expires"" : 57723
            },
            ""friends"" : [{
                ""id"" : 2347484,
                ""name"" : ""Bruce Wayne""
            },
            {
                ""id"" : 996236,
                ""name"" : ""Clark Kent""
            }]
        }";
    
    var obj = (JObject)JsonConvert.DeserializeObject(json);
    Type type = typeof(int);
    var i1 = System.Convert.ChangeType(obj["id"].ToString(), type);
    var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);
    

提交回复
热议问题