[Solved] Sequence contains more than one element error

Jun 13, 2009 at 11:18 PM

"{\"short\":{\"original\":\"http:\\/\\/www.contrast.ie\\/blog\\/online-marketing-2009\\/\",\"short\":\"m2sqc6\",\"shortened\":\"http:\\/\\/short.ie\\/m2sqc6\",\"error\":{\"code\":0,\"msg\":\"No action taken\"}}}"

This is throwing a "Sequence contains more than one element". Here's the stacktrace:

  StackTrace:
       at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
       at Newtonsoft.Json.JsonSerializer.CreateAndPopulateObject(JsonReader reader, Type objectType)
       at Newtonsoft.Json.JsonSerializer.CreateObject(JsonReader reader, Type objectType, Object existingValue, JsonConverter memberConverter)
       at Newtonsoft.Json.JsonSerializer.SetObjectMember(JsonReader reader, Object target, Type targetType, String memberName)
       at Newtonsoft.Json.JsonSerializer.PopulateObject(Object newObject, JsonReader reader, Type objectType)
       at Newtonsoft.Json.JsonSerializer.CreateAndPopulateObject(JsonReader reader, Type objectType)
       at Newtonsoft.Json.JsonSerializer.CreateObject(JsonReader reader, Type objectType, Object existingValue, JsonConverter memberConverter)
       at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
       at Newtonsoft.Json.JavaScriptConvert.DeserializeObject(String value, Type type, JsonConverter[] converters)
       at Newtonsoft.Json.JavaScriptConvert.DeserializeObject[T](String value, JsonConverter[] converters)
       at Newtonsoft.Json.JavaScriptConvert.DeserializeObject[T](String value)
       at Tyrolean.ShortieSharp.Shortie.DeserializeJSON(String apiCall) in C:\Users\PhilSmith\Documents\Visual Studio 2008\Projects\ShortieSharp\Shortie.cs:line 64

 

Finally here's the Object I'm deserializing too:

    [Serializable]
    [XmlRoot("short")]
    [JsonObject(MemberSerialization.OptIn)]
    public class Shortie
    {
        [JsonProperty("original")]
        [XmlElement("original")]
        public String Original { get; set; }

        [JsonProperty("shortened")]
        [XmlElement("shortened")]
        public String Shortened { get; set; }

        [JsonProperty("short")]
        [XmlElement("short")]
        public String Short { get; set; }
    }

I reckon the error is that "Short" is appearing in the json string twice, and as I'm new to json.net I'm not sure how to deal with it. Any suggestions would be great.

Coordinator
Jun 15, 2009 at 11:41 AM

There is an outer object with a short property which you don't want to serialize. You want to serialize the object in that property.

Do something like this:

JObject o = JObject.Parse(json);

Shortie s = JsonConvert.DeserializeObject<Shortie>(o["short"].ToString());

Jun 15, 2009 at 8:06 PM

Thanks James, that's fixed it.