Could not determine JSON object type when adding custom object to JObect

May 16, 2010 at 3:07 PM

Hi!

I'm trying to add a custom object to a JObect but I get the following error:

"Could not determine JSON object type"

The object I'm trying to add is of the type List<myDataType>.

The code is somewhere along the lines of this:

 

public class myDataType{
public string testValue1{get;set;}
public otherDataType testValue2{get;set;}
etc..
}

[WebMethod]
public string returnTestJson(){
List<myDataType> test = myDataTypeTasks.GetMyDataTypeCollection();
JObject o = new JObject();
o.Add("message", "bla bla bla");
o.Add("data", test); return JsonConvert.SerializeObject(o) }

 

Is what I'm trying to do possible or should I serialize from something else than a JObject? And if so - what could I use instead?

Regards,

Peter

 

May 17, 2010 at 6:07 PM
Edited May 17, 2010 at 7:45 PM
perhaps you can try this?
    public class testClass
    {
      public string message;
      public List<myDataType> data;
    }

[WebMethod]
public string returnTestJson(){
  List<myDataType> test = myDataTypeTasks.GetMyDataTypeCollection();
  var o = new testClass { message = "bla bla bla", data = test };
  return JsonConvert.SerializeObject(o);
}
Coordinator
May 18, 2010 at 7:47 AM
Edited May 18, 2010 at 8:05 AM

Only classes that derive from JToken be a child of another JObject/JArray.

I suggest you call JObject.FromObject(test) to convert your custom class to a JObject and then add the result.