【问题标题】:Json Converting complex dictionary<customobject, string>Json 转换复杂字典<customobject, string>
【发布时间】:2020-06-25 14:15:39
【问题描述】:

您在 Azure Functions 中使用 Newtonsoft 时遇到了一点 Json 转换问题。

我有一个 HttpTrigger 函数,并且正在接收一个 json 字符串,然后将其转换为我的复杂对象。

我的目标是能够将我的 json 字符串(如下)转换为 c# Dictionary&lt;AppLanguage, string&gt;() 对象。

我感觉它无法读取 key 中的整数并将其转换为我的枚举值。所以我想有一个配置?

 System.Private.CoreLib: Exception while executing function: MyAppBranchFunctions. Newtonsoft.Json: Unexpected token StartArray when parsing enum. Path 'Texts.Tutorials', line 1, position 382828.

json 看起来像这样:

{
"xxx":
    {
    "Texts":{"Tutorials":[{"Key":1,"Value":"tutorial"},{"Key":4,"Value":""},{"Key":5,"Value":""},{"Key":6,"Value":""},{"Key":7,"Value":""},{"Key":8,"Value":""},{"Key":9,"Value":""},{"Key":10,"Value":""},{"Key":2,"Value":""},{"Key":3,"Value":""}]
    }
}

类的签名如下:

public class Texts
    {
    [JsonConverter(typeof(StringEnumConverter))]
    public Dictionary<AppLanguage, string> Tutorials { get; set; }
    }

[JsonConverter(typeof(StringEnumConverter))]
    public enum AppLanguage
    {
        /// <summary>
        /// german
        /// </summary>
        [EnumMember(Value = "de")]
        de,
        /// <summary>
        /// english
        /// </summary>
        [EnumMember(Value = "en")]
        en,
        /// <summary>
        /// french
        /// </summary>
        [EnumMember(Value = "fr")]
        fr,

【问题讨论】:

  • AppLanguage 是一个整数,而不是一个对象。枚举本质上是数值的别名。您是在问如何使用枚举的名称而不是其值进行序列化?
  • 查看更多代码会很有帮助。例如,进行转换的代码。
  • @mlibby 没有。它是 Azure Functions - 它会自动转换。但是,我所做的只是使用默认的 JsonConvert Newtonsoft.Json.JsonConvert.DeserializeObject(req);
  • @PanagiotisKanavos - 我的 cosmos 数据库中有字符串。我有一个 api,它从 cosmos db(它已经 int)获取 json 并将其发送到我的 azure 函数应用程序。我在我的函数应用程序中收到整数,但不幸的是它没有转换字典
  • 看起来字典被序列化为键/值对数组。要将这样的数组反序列化为字典,请参阅 Newtonsoft Json Deserialize Dictionary as Key/Value list from DataContractJsonSerializerSerialize dictionary as array (of key value pairs)。此外,您的 AppLanguage 枚举没有足够的值来反序列化 JSON 中显示的所有键值。另外,由于键值是整数而不是字符串,所以这里不需要StringEnumConverter

标签: c# azure json.net azure-functions


【解决方案1】:

在我的例子中,我必须先将我的 json 对象序列化为实际的 json,然后才能将它作为 JsonBody 添加到我的 RestSharp Post 中。我喜欢 request.AddJsonBody(myObject) 而不是 request.AddJsonBody(jsonOfMyObject) 现在解决了我的问题。

我猜也应该发布我的“发布”代码。

感谢您的回复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2016-11-20
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多