0

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.

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.