使用JsonConvert C#反序列化包含字典对象的对象

时间:2019-05-29 06:24:35

标签: c# deserialization

我正在尝试序列化下面定义的对象。使用Newtonsoft JsonConvert可以正确执行此操作。这将返回一个字符串。 当我尝试将字符串反序列化回定义的对象时,它将不起作用并引发异常

/**
 * Converts an Integer array to an ArrayList of the same type.
 */
private static java.util.ArrayList<Integer> toArrayList(Integer[] array) {              
    return new java.util.ArrayList<>(Arrays.asList(array));
}

/**
 * return the sum of the second half of items in the given list.
 */
public static int sumSecondHalfItems(final ArrayList<Integer> list) {

    /* Get the upper half of list size value */
    float quotient = (float)list.size() / 2;
    int upper = (int) Math.ceil(quotient);
    /*
     * Here we loop through the upper portion of the list,
     * and retrieve the list elements with a getter method
     */
    int sum = 0;
    for(int i = upper - 1; i < list.size(); i++) {
        sum += list.get(i);
    }
    return sum;
}

public static void main(String[] args) {
    /*
     * Strating off with a primitive array of numbers
     */
    Integer[] a1 = new Integer[]{ 1, 2, 3, 4, 5 };
    Integer[] a2 = new Integer[]{ 6, 7, 8, 9, 10, 11 };
    /*
     * Convert Integer array to ArrayList to fit your example
     */
    int result1 = sumSecondHalfItems(toArrayList(a1));
    int result2 = sumSecondHalfItems(toArrayList(a2));

    System.out.printf("Result of array %s is: %d%n", Arrays.toString(a1), result1);
    System.out.printf("Result of array %s is: %d%n", Arrays.toString(a2), result2);
}

出现以下错误

  

无法将当前JSON数组(例如[1,2,3])反序列化为type   'System.Collections.Generic.IDictionary private class PlotSetFeatureStateInfo { public IDictionary<int,IDictionary<AxisTypeAndUnitInfo,ManualScaleInfo>> PersistentScaleInfo { get; set; } public IDictionary<Guid,ScaleType> PlotIdVsLocalScaleType { get; set; } public IDictionary<Guid,IDictionary<AxisTypeAndUnitInfo, PlotScales.PersistentScaleData>> PlotIdVsPersistentScaleData { get; set;} } var foo = new FeatureStateInfo { //Fill values }; var res = JsonConvert.SerializeObject(foo); var deserializedProperty = JsonConvert.DeserializeObject<FeatureStateInfo>(res);//Throws error 2 [Axis,ManualScale]]   因为该类型需要一个JSON对象(例如{“ name”:“ value”})   正确反序列化。要解决此错误,请将JSON更改为   JSON对象(例如{“ name”:“ value”})或将反序列化类型更改为   实现集合接口的数组或类型(例如   ICollection,IList),例如可以从JSON反序列化的List   数组。还可以将JsonArrayAttribute添加到类型中以强制将其   从JSON数组反序列化

发布示例JSON,无需进行任何编辑。这是有效的json。

2[System.Int32,System.Collections.Generic.IDictionary

解决方案: 我根据大家的建议修改了班级,如下所示。 这对我来说很好

{"PersistentScaleInfo":[{"Key":1,"Value":[{"Key":{"AxisType":0,"UnitInfo":{"UnitId":"601988e7-06a1-4dfd-9bba-535989b3afba","SubunitId":"00000000-0000-0000-0000-000000000000"}},"Value":{"Units":"Hz ","MaxScale":400,"MinScale":0.062,"IsAuto":false,"Axes":"X","AxisType":0,"UnitInfo":{"UnitId":"601988e7-06a1-4dfd-9bba-535989b3afba","SubunitId":"00000000-0000-0000-0000-000000000000"},"IsMinLessThanMax":true}},{"Key":{"AxisType":1,"UnitInfo":{"UnitId":"250f1aea-b8e3-4a4d-98e0-f60abded10a4","SubunitId":"94d2baf0-3bc0-41f7-b207-d8ce54e65e35"}},"Value":{"Units":"in/s rms","MaxScale":0.015,"MinScale":0,"IsAuto":false,"Axes":"Y","AxisType":1,"UnitInfo":{"UnitId":"250f1aea-b8e3-4a4d-98e0-f60abded10a4","SubunitId":"94d2baf0-3bc0-41f7-b207-d8ce54e65e35"},"IsMinLessThanMax":true}}]}],"PlotIdVsLocalScaleType":[{"Key":"5ef394a9-98ad-4f52-b916-b698ae4ef351","Value":2}],"PlotIdVsPersistentScaleData":[{"Key":"5ef394a9-98ad-4f52-b916-b698ae4ef351","Value":[{"Key":{"AxisType":0,"UnitInfo":{"UnitId":"601988e7-06a1-4dfd-9bba-535989b3afba","SubunitId":"00000000-0000-0000-0000-000000000000"}},"Value":{"ManualScaleRange":{"MaxScale":400,"MinScale":0.062},"IsVisibleOnView":true,"IsAutoChecked":false,"AreManualScalesSet":true}},{"Key":{"AxisType":1,"UnitInfo":{"UnitId":"250f1aea-b8e3-4a4d-98e0-f60abded10a4","SubunitId":"94d2baf0-3bc0-41f7-b207-d8ce54e65e35"}},"Value":{"ManualScaleRange":{"MaxScale":0.015,"MinScale":0},"IsVisibleOnView":true,"IsAutoChecked":false,"AreManualScalesSet":true}}]}]}

谢谢:)

1 个答案:

答案 0 :(得分:0)

我根据您的json创建了一个模型并进行了尝试。一切正常。

class Program
    {

        static void Main(string[] args)
        {
            string json = @"{ 'PersistentScaleInfo':[{'Key':1,'Value':[{'Key':{'AxisType':0,'UnitInfo':{'UnitId':'601988e7 - 06a1 - 4dfd - 9bba - 535989b3afba','SubunitId':'00000000 - 0000 - 0000 - 0000 - 000000000000'}
},'Value':{'Units':'Hz ','MaxScale':400,'MinScale':0.062,'IsAuto':false,'Axes':'X','AxisType':0,'UnitInfo':
{'UnitId':'601988e7-06a1-4dfd-9bba-535989b3afba','SubunitId':'00000000-0000-0000-0000-000000000000'},'IsMinLessThanMax':true}},
{'Key':{'AxisType':1,'UnitInfo':{'UnitId':'250f1aea-b8e3-4a4d-98e0-f60abded10a4','SubunitId':'94d2baf0-3bc0-41f7-b207-d8ce54e65e35'}},
'Value':{'Units':'in/s rms','MaxScale':0.015,'MinScale':0,'IsAuto':false,'Axes':'Y','AxisType':1,

'UnitInfo':{'UnitId':'250f1aea-b8e3-4a4d-98e0-f60abded10a4','SubunitId':'94d2baf0-3bc0-41f7-b207-d8ce54e65e35'},
'IsMinLessThanMax':true}}]}],'PlotIdVsLocalScaleType':[{'Key':'5ef394a9-98ad-4f52-b916-b698ae4ef351','Value':2}],


    'PlotIdVsPersistentScaleData':[{'Key':'5ef394a9-98ad-4f52-b916-b698ae4ef351','Value':[{'Key':{'AxisType':0,


    'UnitInfo':{'UnitId':'601988e7-06a1-4dfd-9bba-535989b3afba','SubunitId':'00000000-0000-0000-0000-000000000000'}},


    'Value':{'ManualScaleRange':{'MaxScale':400,'MinScale':0.062},'IsVisibleOnView':true,'IsAutoChecked':false,'AreManualScalesSet':true}},

    {'Key':{'AxisType':1,'UnitInfo':{'UnitId':'250f1aea-b8e3-4a4d-98e0-f60abded10a4','SubunitId':'94d2baf0-3bc0-41f7-b207-d8ce54e65e35'}},
    'Value':{'ManualScaleRange':{'MaxScale':0.015,'MinScale':0},'IsVisibleOnView':true,'IsAutoChecked':false,'AreManualScalesSet':true}}]}]}";


           // var res = JsonConvert.SerializeObject(foo);
            var deserializedProperty = JsonConvert.DeserializeObject<RootObject>(json);//Throws error

            foreach (var item in deserializedProperty.PlotIdVsPersistentScaleData)
            {
                Console.WriteLine(item.Value);
                foreach (var item2 in item.Key)
                {
                    Console.WriteLine(item.Key);
                }
            }



            Console.Read();

        }
    }

根据您的Json,您的模型如下所示

public class UnitInfo
{
    public string UnitId { get; set; }
    public string SubunitId { get; set; }
}

public class Key
{
    public int AxisType { get; set; }
    public UnitInfo UnitInfo { get; set; }
}

public class UnitInfo2
{
    public string UnitId { get; set; }
    public string SubunitId { get; set; }
}

public class Value2
{
    public string Units { get; set; }
    public double MaxScale { get; set; }
    public double MinScale { get; set; }
    public bool IsAuto { get; set; }
    public string Axes { get; set; }
    public int AxisType { get; set; }
    public UnitInfo2 UnitInfo { get; set; }
    public bool IsMinLessThanMax { get; set; }
}

public class Value
{
    public Key Key { get; set; }
    public Value2 Value_ { get; set; }
}

public class PersistentScaleInfo
{
    public int Key { get; set; }
    public List<Value> Value { get; set; }
}

public class PlotIdVsLocalScaleType
{
    public string Key { get; set; }
    public int Value { get; set; }
}

public class UnitInfo3
{
    public string UnitId { get; set; }
    public string SubunitId { get; set; }
}

public class Key2
{
    public int AxisType { get; set; }
    public UnitInfo3 UnitInfo { get; set; }
}

public class ManualScaleRange
{
    public double MaxScale { get; set; }
    public double MinScale { get; set; }
}

public class Value4
{
    public ManualScaleRange ManualScaleRange { get; set; }
    public bool IsVisibleOnView { get; set; }
    public bool IsAutoChecked { get; set; }
    public bool AreManualScalesSet { get; set; }
}

public class Value3
{
    public Key2 Key { get; set; }
    public Value4 Value { get; set; }
}

public class PlotIdVsPersistentScaleData
{
    public string Key { get; set; }
    public List<Value3> Value { get; set; }
}

public class RootObject
{
    public List<PersistentScaleInfo> PersistentScaleInfo { get; set; }
    public List<PlotIdVsLocalScaleType> PlotIdVsLocalScaleType { get; set; }
    public List<PlotIdVsPersistentScaleData> PlotIdVsPersistentScaleData { get; set; }
}