7

我有一個模型,它看起來像這樣:嵌套字符串反序列化模型表示在C#中的JSON數據

class Nested{ 
    public string Name {get; set;} 
    public int Id {get; set;} 
} 

class Model{ 
    [JsonProperty] 
    public Nested N {get; set;} 
    public string Name {get; set;} 
    public int Id {get; set;} 
} 

和該標記是這樣的:

<input asp-for="Name"> 
<input asp-for="id"> 
<input type="hidden" name="n" value="@JsonConvert.SerializeObject(new Nested())"> 

然而,當我發佈這種形式反向失敗的反序列化,因爲N字段看起來像編碼兩次。因此,此代碼的工作:

var b = JsonConvert.DeserializeAnonymousType(model1, new { N = ""}); 
var c = JsonConvert.DeserializeObject<Nested>(b.N); 

但是這一次失敗:

var d = JsonConvert.DeserializeAnonymousType(model1, new {N = new Nested()}); 

我需要的是使其與JsonConvert.DeserializeObject<Model>(model1)工作。我應該改變什麼才能使它工作?


例如:

{"name":"Abc","id":1,"n":"{\"id\":2,\"name\":\"BBB\"}"} 

this question描述,但我在尋找一個優雅,簡單的解決方案,這是不提出同樣的問題。

+3

沒有示例JSON數據的JSON序列化問題? – niksofteng

+0

那麼,我添加了一個例子,但是基於類似問題和情況的鏈接,反序列化在一個案例中起作用,在其他案例中不起作用 - 很明顯,json結構不是問題。那麼,即使問題已經確定 - 解決唯一的問題。 – Natasha

回答

2
class Nested{ 
    public string Name {get; set;} 
    public int Id {get; set;} 
} 

class Model{ 
    [JsonProperty] 
    public string N { 
    get { 
     return JsonConverter.DeserializeObject<Nested>(Nested); 
    } 
    set{ 
     Nested = JsonConverter.SerializeObject(value); 
    } 
    } 

    // Use this in your code 
    [JsonIgnore] 
    public Nested Nested {get;set;} 

    public string Name {get; set;} 
    public int Id {get; set;} 
} 
+0

這是一個很好的方式來使這個工作的確切場景,但事實上,這樣的代碼將需要在每個模型具有類似的結構看起來相當失望。 –

+0

@silent_coder對於一次性使用,這一個是最簡單的,否則你當然可以編寫一些接口和JsonDeserializer,並註冊它,所有工作都是一次性使用太多。 –

-1

嘗試

var d = JsonConvert.DeserializeAnonymousType(model1, new {N = new Nested(), 
     Name = "", Id = 0}); 
0

我有類似的問題,但在相反的方向(由於EF代理和的東西,歷史悠久)

但我要說,這可能是一個很好的提示你的,我做這在我的啓動,對ConfigureServices方法:

// Add framework services. 
services.AddMvc().AddJsonOptions(options => 
     { 
      // In order to avoid infinite loops when using Include<>() in repository queries 
      options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
     }); 

我希望它可以幫助您解決問題。

胡安

0

,你可以用自己的代碼自己serialize它,使用這樣的

[Serializable] 
class Model{ 
    [JsonProperty] 
    public Nested N {get; set;} 
    public string Name {get; set;} 
    public int Id {get; set;} 
protected Model(SerializationInfo info, StreamingContext context) 
     { 
      Name = info.GetString("Name"); 
      Id = info.GetInt32("Id"); 
      try { 
      child = (Model)info.GetValue("N", typeof(Model)); 
     } 

     catch (System.Runtime.Serialization.SerializationException ex) 
     { 
      // value N not found 
     } 

     catch (ArgumentNullException ex) 
     { 
      // shouldn't reach here, type or name is null 
     } 

     catch (InvalidCastException ex) 
     { 
      // the value N doesn't match object type in this case (Model) 
     } 
     } 
} 

Runtime.Serialization

東西,一旦你使用模型類作爲您的參數,它會自動使用該串行我們剛剛做到了。