TheQuestioner
TheQuestioner

Reputation: 722

Converting JSON to an Object

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": "[email protected]",
    "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

Upvotes: 0

Views: 218

Answers (3)

Norman M
Norman M

Reputation: 243

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.

Upvotes: 3

JustOnUnderMillions
JustOnUnderMillions

Reputation: 3795

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 :)

Upvotes: 1

Sherif
Sherif

Reputation: 11943

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#.

Upvotes: 2

Related Questions