如何在JSON.Net中获得JsonProperty的名称? [英] How do I get the name of a JsonProperty in JSON.Net?

查看:745
本文介绍了如何在JSON.Net中获得JsonProperty的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的课程:

I have a class like so:

[JsonObject(MemberSerialization.OptIn)]
public class foo
{
     [JsonProperty("name_in_json")]
     public string Bar { get; set; }
     // etc. 
     public Dictionary<string, bool> ImageFlags { get; set; }
}

JSON最初是从CSV文件生成的,每行代表一个foo对象-它基本上是平坦的,因此我需要将某些键映射到imageflags.

The JSON is generated from a CSV file originally, each line representing a foo object - it's basically flat, so I need to map certain keys to imageflags.

我尝试根据示例此处.

这似乎可以很好地映射标志,但是无法设置常规属性-它查找的是"bar"而不是"name_in_json".

This seems to map the flags fine, but it fails setting normal properties - it looks for 'bar' instead of 'name_in_json'.

我该如何为foo类型的对象获取'name_in_json'值?

How would I go about getting 'name_in_json' value for an object of type foo?

编辑:

edit:

当前解决方案:

 var custAttrs = objectType.GetProperties().Select(p =>     p.GetCustomAttributes(typeof(JsonPropertyAttribute), true)).ToArray();
 var propNames = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray();
 Dictionary<string, string> objProps = new Dictionary<string, string>();
 for (int i = 0; i < propNames.Length; i++) 
     // not every property has json equivalent...
     if (0 == custAttrs[i].Length)
     {
         continue;
     }

     var attr = custAttrs[i][0] as JsonPropertyAttribute; 
     objProps.Add(attr.PropertyName.ToLower(), propNames[i].ToLower());
 }

推荐答案

好的,在上面的示例中,您从类型中使用以下所有属性名称:

Okay, in the example above you get all property names from type with:

var objProps = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray();

因此,您仅使用实际的属性名称,而应该使用JsonProperty的自定义属性.aspx"rel =" nofollow> GetCustomAttributes 方法,并从中获取json属性名称.

So you use only actual property name, what youshould do instead is for each property get custom attribute of type JsonProperty using GetCustomAttributes method, and get json property name from it.

这篇关于如何在JSON.Net中获得JsonProperty的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆