[英]Printing out the first index of an array in JSON format
我正在嘗試以JSON格式打印出數組的第一個索引。
使用代碼:
storeInformation = myStoreInfoTable;
strResponseOutput = JsonConvert.SerializeObject(storeInformation);
結果如下:
[
{
"distance": 0,
"descr": "Toronto",
"address": "1300 Castlefield Avenue",
"city": "Toronto"
},
{
"distance": 7.1121883392,
"descr": "Etobicoke - North",
"address": "Resources Road",
"city": "Etobicoke"
}
]
我試圖獲得第一個索引的方法是:
storeInformationRow = dtbStoreInformation.Rows[0];
strResponseOutput = JsonConvert.SerializeObject(storeInformationRow);
我得到的是:
{
"RowError": "",
"RowState": 2,
"Table": [
{
"distance": 0.0000000000,
"descr": "Toronto",
"address": "1300 Castlefield Avenue",
"city": "Toronto"
},
{
"distance": 7.1121883392,
"descr": "Etobicoke - North",
"address": "Resources Road",
"city": "Etobicoke"
}
]
}
我想要的結果就是
{
"distance": 0.0000000000,
"descr": "Toronto",
"address": "1300 Castlefield Avenue",
"city": "Toronto"
}
幫助任何人?
在我看來,JSON序列化程序正在發生麻煩,因為它不知道如何正確序列化DataRow
。 這是第一段和第二段代碼之間的唯一區別。
如果查看DataRow
類的MSDN文檔,您會發現DataRow
具有顯示的屬性( RowError
, RowState
和Table
)以及許多其他屬性。
為了解決您的問題,我建議使用以下兩種方法之一:
創建一個新的DataTable
並添加要序列化的DataRow
,然后在其上調用JsonConvert.SerializeObject()
。
將列(距離,描述,地址和城市)映射到另一個類( Store
或其他),然后嘗試序列化該對象。 從我在JsonConvert
文檔中閱讀的內容JsonConvert
這是可能的(類屬性已正確映射到JSON對象上)。
讓我知道事情的后續!
您可以使用:
var row = dtbStoreInformation.Rows [0];
string strResponseOutput = new {
distance = row[0].ToString(),
descr= row[1].ToString(),
address = row[2].ToString(),
city = row[2].ToString()}.ToJson();
不要忘記名稱空間ServiceStack.Text
的包含
您還可以創建一個匿名對象
var obj = jsonString = new {
distance = row[0].ToString(),
descr= row[1].ToString(),
address = row[2].ToString(),
city = row[2].ToString()}
strResponseOutput = JsonConvert.SerializeObject(obj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.