2017-09-05 61 views
0

我使用ASP.NET MVC 5在.NET Framework中運行。我有一個MVC控制器使用Newtonsoft.Json(或json.net)構建一個漂亮的JSON對象。我遇到麻煩的是,當我返回使用JsonResult方法Json(JSONdotnetObject)我的JSON,我結束了與具有相同的結構,我期望,但一切都是空談JArrays像這樣的結果:JSON對象在使用JsonResult返回時序列化爲空括號

預期:

{ 
    "prop": { 
     ... some stuff ... 
    }, 
    "another prop": { 
     ... more stuff ... 
    } 
} 

實際:

[ 
    [ 
     ... empty ... 
    ], 
    [ 
     ... also empty ... 
    ] 
] 

而這裏的代碼:

public ActionResult methodName(string input) { 
    JObject myJSON = new JObject(); 

    // Populate myJSON with children 
    foreach (Thing thing in ExistingEntityFrameworkCustomClass) { 
     JObject newChild = new JObject(); 

     // Add some props to newChild using newChild["propName"] = thing.Property 

     myJSON.Add(newChild.UniqueIdTakenFromEntity.ToString(), newChild); 
    } 

    // The JsonResult successfully populates it's Data field with myJSON before returning. 
    return Json(myJSON, JsonRequestBehavoir.AllowGet); 
} 

這不是確切的結構,但希望能說明我正在經歷的事情。我已經在VS中通過程序逐行,JsonResult對象正確地將JObject保存在JsonResult.Data字段中,但是當它返回出錯時,ASP.NET執行的序列化會導致我失去美麗的JSON對象:*(

我已經簡單地返回JObject而不是從方法的ActionResult解決此問題的工作,但這並不理想,因爲我那麼必須手動設置使用Result.ContentType這感覺就像一個黑客攻擊的響應頭。

讓我知道你是否有任何想法或可以使用更多的細節。謝謝您的時間。

+1

你需要添加一些代碼,以便我們可以看到你在做什麼 – JSON

+0

會做。我將添加一些基於代碼的基本實現。 –

+0

如果它是空的,我們需要看看你是如何填充對象。 – Amy

回答

3

問題是MVC Controller類中的Json方法在內部使用JavaScriptSerializer(不是Json.Net),並且不知道如何正確地序列化JObject。嘗試使用Content方法來代替:

public ActionResult methodName(string input) { 
    JObject myJSON = new JObject(); 

    // Populate myJSON with children 

    return Content(myJSON.ToString(), "application/json", Encoding.UTF8); 
} 

或者,您也可以實現自己的JsonNetResult類如圖詹姆斯·牛頓 - 王的博客文章,ASP.NET MVC and Json.NET

+0

這對我來說非常合適。感謝您的快速簡單的解釋和代碼片段。 –

+1

很高興我能幫到你。 –