Json Import fails - C#

2.3k Views Asked by At

I have the following class structure

public class AreaFields
{
    public List<Fields> Fields { set; get; }
}

public class Fields
{
    public string Name { set; get; }
    public string Value {set; get; }
}

When I export to Json using Jayrock.Json.Conversion.JsonConvert.ExportToString(List<AreaField> obj), everything works fine. The problem is when I attempt to import it back to a list of AreaField, the native import fails. What I am trying to is

Jayrock.Json.Conversion.JsonConvert.Import(strJson)

Is there a way to maybe override the import method?

EDIT: Yes, jayrock knows the type of the object. My guess it has to do something with me serializing a list.

Export -
List<AreaField> list = GetAListOfAreaFields();
string sJson = Jayrock.Json.Conversion.JsonConvert.ExportToString(list)

Import -
List<AreaField> list = (AreaField)JsonConvert.Import(typeof(AreaField, sJson);

Exception - Cannot import AreaField from a JSON Array value.

3

There are 3 best solutions below

0
On

List<> won't works, but array works. Like this:

AreaField[] list = JsonConvert.Import<AreaField[]>(sJson);
0
On

It looks like you're exporting a List<AreaField> but attempting to import an AreaField (singular). Try:

List<AreaField> list = (List<AreaField>)JsonConvert.Import(typeof(List<AreaField>, sJson);
0
On

"It doesn't work" is not a good start. Exception? Wrong data? Does Jayrock know the type of the object?

AreaFields af = (AreaFields)Jayrock.Json.Conversion.JsonConvert.Import(typeof(AreaFields), strJson);