gpt4 book ai didi

json - MVC3 JSON 序列化 : How to control the property names?

转载 作者:行者123 更新时间:2023-12-02 20:34:57 24 4
gpt4 key购买 nike

我想将一个简单的对象序列化为 JSON:

public class JsonTreeNode
{
[DataMember(Name = "title")]
public string Title { get; set; }

[DataMember(Name = "isFolder")]
public bool IsFolder { get; set; }

[DataMember(Name = "key")]
public string Key { get; set; }

[DataMember(Name = "children")]
public IEnumerable<JsonTreeNode> Children { get; set; }

[DataMember(Name = "select")]
public bool SelectedOnInit { get; set; }
}

但每当我这样做时:

return Json(tree, JsonRequestBehavior.AllowGet);

属性名称与[DataMember]部分中指定的不同,但类似于直接在类中定义的名称,例如对于SelectOnInit,它不是select,而是SelectOnInit

我做错了什么?

最佳答案

我通过使用此问题答案中提供的技术解决了该问题:

ASP.NET MVC: Controlling serialization of property names with JsonResult

这是我制作的类(class):

/// <summary>
/// Similiar to <see cref="JsonResult"/>, with
/// the exception that the <see cref="DataContract"/> attributes are
/// respected.
/// </summary>
/// <remarks>
/// Based on the excellent stackoverflow answer:
/// https://stackoverflow.com/a/263416/1039947
/// </remarks>
public class JsonDataContractActionResult : ActionResult
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
/// <param name="data">Data to parse.</param>
public JsonDataContractActionResult(Object data)
{
Data = data;
}

/// <summary>
/// Gets or sets the data.
/// </summary>
public Object Data { get; private set; }

/// <summary>
/// Enables processing of the result of an action method by a
/// custom type that inherits from the ActionResult class.
/// </summary>
/// <param name="context">The controller context.</param>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");

var serializer = new DataContractJsonSerializer(Data.GetType());

string output;
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, Data);
output = Encoding.UTF8.GetString(ms.ToArray());
}

context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.Write(output);
}
}

用法:

    public ActionResult TestFunction()
{
var testObject = new TestClass();
return new JsonDataContractActionResult(testObject);
}

我还必须修改初始类:

// -- The DataContract property was added --
[DataContract]
public class JsonTreeNode
{
[DataMember(Name = "title")]
public string Title { get; set; }

[DataMember(Name = "isFolder")]
public bool IsFolder { get; set; }

[DataMember(Name = "key")]
public string Key { get; set; }

[DataMember(Name = "children")]
public IEnumerable<JsonTreeNode> Children { get; set; }

[DataMember(Name = "select")]
public bool SelectedOnInit { get; set; }
}

关于json - MVC3 JSON 序列化 : How to control the property names?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7260924/

24 4 0