将JSON反序列化为CSLA对象列表

时间:2017-01-24 07:39:28

标签: c# json csla

我无法使用CSLA将JSON转换为对象格式。

这是我的JSON:

[
  {\"SupplyChainNodeId\":11046,
  \"PhoneNumber\":\"7704428881\",
  \"BranchNumber\":\"172\",
  \"BranchNameRaw\":\"\",
  \"BranchName\":\"AlpharettaGA #172\",
  \"Distance\":0.0,
  \"Street\":\"5610 Mcginnis Ferry Rd Bldg1\",
  \"Street2\":\"\",
  \"City\":\"Alpharetta\",
  \"StateCode\":\"GA\",
  \"PostalCode\":\"30005-3925\",
  \"Latitude\":\"34.0888920000000000\",
  \"Longitude\":\"-84.1972940000000000\",
  \"Description\":\"\",\"DisplayName\":\"172 - \",
  \"DivisionID\":\"\",
  \"AddressID":\"05815842-9fb1-45f2-86c4-5751b49413b9\",
  \"IsBusy\":false,
  \"IsSelfBusy\":false}
]

**班级格式:**

[Serializable]
    public class BranchInfos : ReadOnlyListBase<BranchInfos, BranchInfo>
    {
}

public static Object PopulateDto(Object dto, string json)
{
    //Get the type of the target dto
    Type type = Type.GetType(dto.GetType().FullName);

    //convert to array if single row of data - this streamlines the deserialization process
    if (!json.StartsWith("["))
    {
        json = "[" + json + "]";
    }

    //Create settings so that not everyfield in dto is required
    var settings = new JsonSerializerSettings();
    settings.MissingMemberHandling = MissingMemberHandling.Ignore;

    //Use the type pulled from dto and the json to populate the dto
    Object jsonObject = JsonConvert.DeserializeObject(json, type, settings);

    //The returned dto can now be casted to the correct dto type
    return (jsonObject);
}

Json使用以下代码行转换为对象格式: -

  List<BranchInfos> branchInfos = new List<BranchInfos>();
  branchInfos = (List<BranchInfos>)PopulateDto(branchInfos, json);

尝试将JSON转换为对象格式时的异常是:

  

{&#34;无法将当前的JSON对象(例如{\&#34; name \&#34;:\&#34; value \&#34;})反序列化为类型&#39; BusinessLayer。 Branch.BranchInfos&#39;因为类型需要一个JSON数组(例如[1,2,3])才能正确反序列化。\ r \ n要解决此错误,要么将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,以便它是一个普通的.NET类型(例如,不是像整数的基本类型,不是像数组或列表那样的集合类型),可以从JSON对象反序列化。 JsonObjectAttribute也可以添加到类型中以强制它从JSON对象反序列化。\ r \ n路由&#39; [0] .SupplyChainNodeId&#39;,第1行,第22位。&#34;}

0 个答案:

没有答案
相关问题