gpt4 book ai didi

c# - 使用 ServiceStack 创建 Json 数组

转载 作者:行者123 更新时间:2023-11-30 14:59:06 25 4
gpt4 key购买 nike

对 .NET 很陌生。仍然没有掌握如何使用字典、列表、数组等的窍门。

我需要生成此 JSON 以便与 SugarCRM 的 REST API 对话:

{
"name_value_list": {
"assigned_user_name": {
"name": "assigned_user_name",
"value": "joe"
},
"modified_by_name": {
"name": "modified_by_name",
"value": "jill"
},
"created_by_name": {
"name": "created_by_name",
"value": "jack"
}
}
}

来自这个 C# POCO,它与 ServiceStack 配合得很好:

public class lead {
public string assigned_user_name { get; set; }
public string modified_by_name { get; set; }
public string created_by_name { get; set; }
}

我必须对很多不同的类进行这种转换,所以我认为创建另一个强类型类是不明智的(ala Costomising the serialisation/serialised JSON in service stack)

我已经查看了 ServiceStack 文档,但也许我在某处遗漏了这方面的示例。

如何以可以扩展到其他 ServiceStack POCO 的方式构建此 JSON?

最佳答案

这会生成正确的 JSON:

        Dictionary<string, Dictionary<string, string>> nameValues = new Dictionary<string, Dictionary<string, string>>();

// Deal with all the properties on the object
IList<PropertyInfo> props = new List<PropertyInfo>(this.GetType().GetProperties());
foreach (PropertyInfo prop in props)
{
Dictionary<string, string> nameValue = new Dictionary<string, string>();
nameValue.Add("name", prop.Name);
object propValue = prop.GetValue(this, null);
if (propValue == null)
{
nameValue.Add("value", string.Empty);
}
else
{
nameValue.Add("value", prop.GetValue(this, null).ToString());
}

nameValues.Add(prop.Name, nameValue);
}

Dictionary<string, object> nameValuesArray = new Dictionary<string, object>();
nameValuesArray.Add("name_value_list", nameValues);
string jsonString = JsonSerializer.SerializeToString<Dictionary<string, object>>(nameValuesArray);

反射的东西是为了我以后可以在任何对象上使用它。

这只是为所需的 JSON 输出构建正确的字典的问题 - 在本例中是字典 -> 字典 -> 字典。反复试验...:/

更新

稍微改变它(感谢 paaschpa)以使用通用的 NameValue 类,因为字典看起来很难看。我也把要求弄错了。 JSON 应该是这样的:

[
{
"name": "id",
"value": "60e03cb3-df91-02bd-91ae-51cb04f937bf"
},
{
"name": "first_name",
"value": "FancyPants"
}
]

你可以这样做:

public class NameValue
{
public string name { get; set; }
public string value { get; set; }
}

public class Lead
{
public string assigned_user_name { get; set; }
public string modified_by_name { get; set; }
public string modified_user_name { get; set; }

public List<NameValue> toNameValues()
{
List<NameValue> nameValues = new List<NameValue>();

IList<PropertyInfo> props = new List<PropertyInfo>(this.GetType().GetProperties());
foreach (PropertyInfo prop in props)
{
NameValue nameValue = new NameValue();

object propValue = prop.GetValue(this, null);
if (propValue != null && !String.IsNullOrEmpty(propValue.ToString()))
{
nameValue.name = prop.Name;
nameValue.value = propValue.ToString();
nameValues.Add(nameValue);
}
}

return nameValues;
}
}

我将原样保留我原来的问题(以及我上面的答案),因为它仍然是一个合法的示例和正确的 JSON。

关于c# - 使用 ServiceStack 创建 Json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17326005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com