簡體   English   中英

使用 JavaScriptSerializer 反序列化 JSON 字符串以返回單個動態對象而不是鍵和值數組

[英]Deserializing JSON string with JavaScriptSerializer to return a single dynamic object instead of an array of keys and values

考慮 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是一個鍵/值對數組:

在此處輸入圖片說明

知道如何將它們反序列化為一個單獨的動態對象,在那里我可以使用以下方法訪問屬性:

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

JsonConvert/NewtonSoft 不是一個選擇。

您可以使用某些ModelDto代替object並將其轉換為它,我的意思是:

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

或者您可以使用以下代碼通過鍵從字典中獲取值:

string buyerRegion = dict["BuyerRegion"];

或者,您可以按照問題評論中的建議使用 ExpandoObject。

在嘗試了幾種方法后,我開始意識到訪問屬性就像調用一樣簡單:

obj["BuyerRegion"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM