I am trying to retrieve the contents of "data" from my JSON response. I believe I've created the classes correctly but I'm messing up the deserialization for the TechProfile class. I get an Exception when trying to set the 'techProfile' variable.
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: P. Path '', line 0, position 0.'
I have reluctantly added a ToString() at the end of the JSONMainResponse.Data parameter, as it doesn't compile without it.
My JSON:
{
"success":true,
"msg":"",
"data":[
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"1","option_type":"Scale","name":"Desktop apps","value":"2"},
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"2","option_type":"Scale","name":"Mobile apps","value":"2"},
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"3","option_type":"Scale","name":"Server apps","value":"5"},
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"4","option_type":"Scale","name":"Hardware dev","value":"2"},
{"categoryName":"Target platform","option_category_id":"1","skill_optionID":"5","option_type":"Scale","name":"Web dev","value":"0"}
]
}
Main code:
string result = postData("http://test.com/test.php");
JSONMain JSONMainResponse = JsonConvert.DeserializeObject<JSONMain>(result);
string success = JSONMainResponse.Success;
string msg = JSONMainResponse.Msg;
TechProfile techProfile = JsonConvert.DeserializeObject<TechProfile>(JSONMainResponse.Data.ToString());
The classes:
public partial class JSONMain
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("msg")]
public string Msg { get; set; }
[JsonProperty("data")]
public TechProfile[] Data { get; set; }
}
public partial class TechProfile
{
[JsonProperty("categoryName")]
public string CategoryName { get; set; }
[JsonProperty("option_category_id")]
public string OptionCategoryId { get; set; }
[JsonProperty("skill_optionID")]
public string SkillOptionId { get; set; }
[JsonProperty("option_type")]
public string OptionType { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
I was over-egging it a bit.
First change made to the JSONMain class:
public List<TechProfile> Data { get; set; }
instead of...
public TechProfile[] Data { get; set; }
Then for the main code, instead of trying to deserialize again, I simply declared a new List of TechProfiles based on JSONMainResponse.Data. See below
string success = JSONMainResponse.Success;
string msg = JSONMainResponse.Msg;
List<TechProfile> data = JSONMainResponse.Data;
foreach(TechProfile tp in data)
{
string categoryName = tp.CategoryName;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.