Reputation: 946
I receive the error "Object serialized to Property. JObject instance expected." when trying to use the following:
SortedList<string,string> results = new SortedList<string,string>();
results.Add("BOBB", "Bob Brattwurst");
results.Add("DANG", "Dan Germany");
results.Add("KON", "Konrad Plith");
JObject output = JObject.FromObject(
new JProperty("suggestions",
new JArray(
from r in results
orderby r.Value
select new JObject(
new JProperty("value", r.Key),
new JProperty("data", r.Value)
)
)
)
);
The error occurs when setting the output variable.
This is placed in a Web service, and the expected Json result should look like:
{
"suggestions": [
{ "value": "BOBB", "data": "Bob Brattwurst" },
{ "value": "DANG", "data": "Dan Germany" },
{ "value": "KON", "data": "Konraid Plith" }
]
}
I've checked against an example i found here: http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm However i don't quite see the issue.
Upvotes: 0
Views: 6963
Reputation: 46
A solution maybe to read the data into an anoymous object, following a similar take to heinzbeinz.
SortedList<string, string> results = new SortedList<string, string>();
results.Add("BOBB", "Bob Brattwurst");
results.Add("DANG", "Dan Germany");
results.Add("KON", "Konrad Plith");
var obj = new
{
Suggestions = results.Select(x => new { Value = x.Key, Data = x.Value }).ToList()
};
var jsonString = JsonConvert.SerializeObject(obj);
Upvotes: 1
Reputation: 3542
you could read your data into a custom data structure (or anonymous types if you prefer), which represents your json:
public class JsonContainer
{
[JsonProperty("suggestions")]
public List<JsonData> Suggestions { get;set; }
}
public class JsonData
{
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("data")]
public string Data { get; set; }
}
// ...
var results = new SortedList<string, string>();
results.Add("BOBB", "Bob Brattwurst");
results.Add("DANG", "Dan Germany");
results.Add("KON", "Konrad Plith");
var container = new JsonDataContainer();
container.Suggestions = results.Select(r => new JsonData
{
Value = r.Key,
Data = r.Value
}).ToList();
var json = JsonConvert.SerializeObject(container);
Upvotes: 2