Reputation: 1511
I am a newbie in .Net and I am creating a desktop application to my website. I am passing data using JSON and Json.NET However I am receiving an error every time I try to decode this string. What could possibly be wrong? How do I decode a multidimensional array.
This is the string I am decoding
{
"api_ver":"1.0",
"request":"user-account-exists",
"date":"2014-08-25 09:57:16",
"data":
{
"user_account_exists":1
}
}
My code is here
json_data = string.Empty;
try
{
json_data = webclient.DownloadString("http://api.mysite.com/?ruser-account-exists");
}
catch (Exception e)
{
Logger.Log(e.Message);
}
_api = !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<api>(json_data) :
new api();
The error is as shown below
Error reading string. Unexpected token: StartObject. Path 'data', line 1, position 86.
I want to deserialize this array into a dictionary
Upvotes: 0
Views: 1919
Reputation: 1587
Try This ?
public class api
{
public string api_ver { get; set; }
public string request { get; set; }
public string date { get; set; }
public Data data { get; set; }
}
public class Data
{
public int user_account_exists { get; set; }
}
api apiObj = JsonConvert.DeserializeObject<api>(json_data) ;
Upvotes: 0
Reputation: 7804
This error occurs because the api
class does not model the json sufficiently.
The model should resemble the following one (generated using Json2CSharp):
public class Api
{
public string api_ver { get; set; }
public string request { get; set; }
public string date { get; set; }
public Data data { get; set; }
}
public class Data
{
public int user_account_exists { get; set; }
}
Optionally you could use dynamic
dynamic values = JsonConvert.DeserializeObject<dynamic>(json_data);
bool exists = (int) values.data.user_account_exists == 1;
Upvotes: 3