douya6229
douya6229
2016-08-26 14:15
浏览 87

将JSON转换为对象

i have a method that sends a POST Request to my PHP API and the API responds with a JSON String return value.

however after using JsonConvert.DeserializeObject() to the JSON result, i am getting this format

{[
  {
    "usr_name": "12-34567",
    "usr_fullname": "LASTNAME, FIRSTNAME MIDDLENAME",
    "usr_emailaddress": "myemail@mail.com",
    "photo_url": "http://mywebsite.com/fetch_photo.php?id=MTItNDA1MDY=",
    "token": "64c420939814c62889ea143d17736841"
  }  
]}

however i am not able to Deserialize it to my Class that is structured like below

public class MyObject
{
    public string usr_name { get; set; }
    public string usr_fullname { get; set; }
    public string usr_emailaddress { get; set; }
    public string photo_url { get; set; }
    public string token { get; set; }
}

i am using Newtonsoft JSON.Net for this purpose, this is my first time dealing with JSON inside C# so i am quite clueless no how or what to do. i've done several research only to find outdated tutorials or questions unlike my returned JSON value

so the php's response looks like this enter image description here

and after trying to deserialize it, it looks like this enter image description here

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dsdqpdjpq16640651
    dsdqpdjpq16640651 2016-08-26 14:19
    已采纳

    Your json string is not valid json - the wrapping {} are invalid. You should check how the json string is generated / encoded inside your php API.

    点赞 评论
  • dongmaijie5200
    dongmaijie5200 2016-08-26 14:22

    If I had to guess, I'd say you serialized this object in PHP from a database query, which typically returns an array of rows. Which is why your JSON is an object with an array that contains an object.

    There's an extra level of indirection in there so you need to remove that to deserialize. Try using array_pop in your PHP to to make sure you're only serializing a single object, or just use the fetch rather than fetchAll equivalent for your database interface in PHP if you only expect a single value. Otherwise, iterate over the array of objects after deserializing in C#.

    点赞 评论
  • duanhui1185
    duanhui1185 2016-08-26 14:24

    That can be a soultion for that in PHP (if your json example is right):

    $obj = new MyClass();//get empty instance
    $arr = json_decode(trim($json,'}{'),true);//get array from json, but fix it first
    //because {[{'key':'value'}]} is not valid!
    $arr = $arr[0];//get sub array with real data
    //bind all data to your object
    array_walk($arr,function($v,$k) use ($obj){ $obj->{$k}=$v; });
    
    print $obj->usr_name;// output: 12-34567
    

    Why is {[{'key':'value'}]} not valid? An Object Member MUST have a name!

    So that would be valid json: {'content':[{'key':'value'}]}.

    UPDATE: Forget this answer!! You want to do this in C# not in PHP :)

    点赞 评论

相关推荐