Converting a JToken (or string) to a given Type

前端 未结 4 1111
予麋鹿
予麋鹿 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);
    
    0 讨论(0)
  • 2020-12-08 09:34
    var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);
    

    throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:

    var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);
    
    0 讨论(0)
  • 2020-12-08 09:43

    I was able to convert using below method for my WebAPI:

    [HttpPost]
    public HttpResponseMessage Post(dynamic item) // Passing parameter as dynamic
    {
    JArray itemArray = item["Region"]; // You need to add JSON.NET library
    JObject obj = itemArray[0] as JObject;  // Converting from JArray to JObject
    Region objRegion = obj.ToObject<Region>(); // Converting to Region object
    }
    
    0 讨论(0)
  • 2020-12-08 09:48

    There is a ToObject method now.

    var obj = jsonObject["date_joined"];
    var result = obj.ToObject<DateTime>();
    

    It also works with any complex type, and obey to JsonPropertyAttribute rules

    var result = obj.ToObject<MyClass>();
    
    public class MyClass 
    { 
        [JsonProperty("date_field")]
        public DateTime MyDate {get;set;}
    }
    
    0 讨论(0)
提交回复
热议问题