使用JavaScriptSerializer反序列化JSON字符串以返回单个动态对象而不是键和值的数组

问题描述 投票:2回答:2

考虑C#中的以下JSON字符串:

{
    "BuyerRegion":"BuyerRegion [0][27]",
    "SellerRegion":"SellerRegion [0][29]",
    "HubRegion":"HubRegion [0][31]",
    "PartNo":"TINT_MNUM [0][3]",
    "BuyerCompID":"BuyerCompId [0][28]",
    "SellerCompId":"SellerCompId [0][30]",
    "HubCompId":"HubCompId [0][32]"
}

然后我尝试使用以下方法将字符串反序列化为C#中的动态对象:

object obj = new JavaScriptSerializer().Deserialize<object>(s); //where s contains the JSON string

但是,返回的obj是键/值对的数组:

enter image description here

任何想法我都可以将它们反序列化为一个动态对象,在这里我可以使用以下方法访问属性:

obj.BuyerRegion //returns "BuyerRegion [0][27]"

JsonConvert / NewtonSoft不是一个选择。

c# json javascriptserializer
2个回答
0
投票

您可以使用某些object代替ModelDto并强制转换为它,]

public class ModelDto {
  public string Key {get;set;}
  public string Value {get;set;}
}

或者您可以使用下面的代码通过键从字典中获取价值:

string buyerRegion = dict["BuyerRegion"];

或者您可以根据对问题的评论中的建议使用ExpandoObject。


0
投票

[尝试了几种方法之后,我意识到访问属性就像调用一样容易:

obj["BuyerRegion"]
© www.soinside.com 2019 - 2024. All rights reserved.