[英]Deserializing a JSON Array of size 1 in c#
我有兩個不同的 JSON 對象,它們的一個屬性略有不同:
string JSONObject1 = "
{
prop1: val1
prop2: {
prop3: val3
prop4: val4
}
}
"
string JSONObject2 = "
{
prop1: val1
prop2: [{
prop3: val3
prop4: val4
}]
}
"
class MyObject
{
string prop1 {get; set;}
MyInnerObject prop2 {get; set;}
}
class MyInnerObject
{
string prop3;
string prop4;
}
JsonConvert.DeserializeObject<MyObject>(JSONObject1) // This works
JsonConvert.DeserializeObject<MyObject>(JSONObject2) // This does not work
如何反序列化 JSONObject2,而不添加新類或修改 MyObject?
更新我的答案,為這個問題提供一個更動態和更可靠的答案。 在處理此解決方案時,OP 問題中提到的問題對我來說變得很明顯,但假設考慮了以下項目列表,您可以使用動態 json 解決此問題。
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting;
using System.Text;
using System.Threading.Tasks;
namespace commandexample
{
class Program
{
static void Main(string[] args)
{
string JSONObject1 = @"
{
prop1: ""val1"",
prop2: {
prop3: ""val3"",
prop4: ""val4""
}
}";
string JSONObject2 = @"
{
prop1: ""val1"",
prop2:[{
prop3: ""val3"",
prop4: ""val4""
}]
}";
var dyn = JsonConvert.DeserializeObject<dynamic>(JSONObject2);
if (dyn.prop2.GetType().Name == "JArray")
{
dyn.prop2 = dyn.prop2[0];
}
string updatedJson = JsonConvert.SerializeObject(dyn);
MyObject result1 = JsonConvert.DeserializeObject<MyObject>(JSONObject1);
MyObject result2 = JsonConvert.DeserializeObject<MyObject>(updatedJson);
}
public class MyObject
{
public string prop1 { get; set; }
public MyInnerObject prop2 { get; set; }
}
public class MyInnerObject
{
public string prop3;
public string prop4;
}
}
}
原帖
如果您知道該數組將始終只包含一項,並且您的 json 文檔中只有一個數組,您可以只對方括號的 json 字符串進行字符串替換。 這將滿足您的特定問題的條件,但如果將來文檔更改以添加其他數組屬性,則可能會導致問題。 真的取決於你的用例。
我可以將此視為一個數據問題,其中一個人試圖讀取由兩個獨立系統生成的 json 文檔,而其中一個系統未正確創建文檔。
JSONObject2 = JSONObject2.Replace("[","").Replace("]","");
//then continue with the Deserialization
JsonConvert.DeserializeObject<MyObject>(JSONObject2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.