Reputation: 33
When I am trying to deserialize my JSON with JSON.Net it gives me invalid values for JSON arrays.
I have simple JSON:
[
{
"PhaseName": "Start",
"Advices": ["Lorem ipsum dolor",
"Lorem ipsum dolor",
"Lorem ipsum dolor"]
},
{
"PhaseName": "In Progress",
"Advices": ["Lorem ipsum dolor",
"Lorem ipsum dolor",
"Lorem ipsum dolor"]
},
{
"PhaseName": "Finish",
"Advices": ["Lorem ipsum dolor",
"Lorem ipsum dolor",
"Lorem ipsum dolor"]
}
]
And a correspondent class in my code:
public class Advices
{
public string PhaseName { get; set; }
public List<string> AdvicesList { get; set; }
}
And a veriable that represents an array of Advices objects:
public class MyAdvices
{
private Advices[] MyAdvicesArrays;
....
So when I am trying to deserialize my JSON like that:
MyAdvicesArrays= JsonConvert.DeserializeObject<Advices[]>(sMyJSON));
JSON.Net populates "Phase Name" property of each object in my MyAdvicesArrays array with correct value but Advices array of each object is invalid: "Could not evaluate expression" if you check them in runtime. I don't get it. What I've done wrong?
Upvotes: 3
Views: 4991
Reputation: 14938
All I did to get this working was to change the definition of the Advices
class:
public class Advice
{
public string PhaseName { get; set; }
public List<string> Advices { get; set; }
}
I changed the class name to just Advice
and AdvicesList
property to Advices
.
Upvotes: 0
Reputation: 8875
No, you're JSON is incorrect as is you Class.
First change your JSON to this:
{
phases:[
{
"PhaseName": "Start",
"Advices": ["Lorem ipsum dolor",
"Lorem ipsum dolor",
"Lorem ipsum dolor"]
},
{
"PhaseName": "In Progress",
"Advices": ["Lorem ipsum dolor",
"Lorem ipsum dolor",
"Lorem ipsum dolor"]
},
{
"PhaseName": "Finish",
"Advices": ["Lorem ipsum dolor",
"Lorem ipsum dolor",
"Lorem ipsum dolor"]
}
]
}
Notice before you weren't declaring you JSON object correctly. Also you need a property for the array.
Now you'll need two classes:
public class AnythinYouWant{
public List<Phase> Phases{get;set;}
}
public class Phase{
public string PhaseName{get;set;}
public List<string> Advices{get;set;}
}
Notice how the first class is for the top level JSON object. The name can be whatever you want. But any property needs to match the name.
Upvotes: 0
Reputation: 13150
Your json
is not valid according to the entities.
In your type change AdvicesList
to Advices
.
public List<string> AdvicesList { get; set; }
Change it to
public List<string> Advices { get; set; }
Upvotes: 1