我可以在属性中指定一个路径来将类中的属性Map到JSON中的子属性吗?

juzqafwq  于 2023-01-10  发布在  其他
关注(0)|答案(7)|浏览(161)

有一些代码Json的DeserializeObject<T>(strJSONData)从Web请求中获取数据并将其转换为类对象(我无法更改)(我可以改变类)。通过用[DataMember(Name = "raw_property_name")]修饰我的类属性,我可以将原始JSON数据Map到我的类中的正确属性。有没有办法将JSON复杂对象的子属性Map到简单属性?这是一个例子:

{
    "picture": 
    {
        "id": 123456,
        "data": 
        {
            "type": "jpg",
            "url": "http://www.someplace.com/mypicture.jpg"
        }
    }
}

除了URL,我不关心图片对象的其他任何部分,因此不想在C#类中设置复杂的对象。我只想设置如下内容:

[DataMember(Name = "picture.data.url")]
public string ProfilePicture { get; set; }

这可能吗?

vecaoik1

vecaoik11#

如果只需要一个额外的属性,一种简单的方法是将JSON解析为JObject,使用ToObject()JObject填充类,然后使用SelectToken()拉入额外的属性。
假设你的类看起来像这样:

class Person
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("age")]
    public string Age { get; set; }

    public string ProfilePicture { get; set; }
}

你可以这样做:

string json = @"
{
    ""name"" : ""Joe Shmoe"",
    ""age"" : 26,
    ""picture"":
    {
        ""id"": 123456,
        ""data"":
        {
            ""type"": ""jpg"",
            ""url"": ""http://www.someplace.com/mypicture.jpg""
        }
    }
}";

JObject jo = JObject.Parse(json);
Person p = jo.ToObject<Person>();
p.ProfilePicture = (string)jo.SelectToken("picture.data.url");

小提琴:https://dotnetfiddle.net/7gnJCK
如果你更喜欢一个更花哨的解决方案,你可以定制一个JsonConverter来使JsonProperty属性像你描述的那样工作。转换器需要在类级别操作,并使用一些反射结合上面的技术来填充所有属性。下面是它的代码:

class JsonPathConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, 
                                    object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        object targetObj = Activator.CreateInstance(objectType);

        foreach (PropertyInfo prop in objectType.GetProperties()
                                                .Where(p => p.CanRead && p.CanWrite))
        {
            JsonPropertyAttribute att = prop.GetCustomAttributes(true)
                                            .OfType<JsonPropertyAttribute>()
                                            .FirstOrDefault();

            string jsonPath = (att != null ? att.PropertyName : prop.Name);
            JToken token = jo.SelectToken(jsonPath);

            if (token != null && token.Type != JTokenType.Null)
            {
                object value = token.ToObject(prop.PropertyType, serializer);
                prop.SetValue(targetObj, value, null);
            }
        }

        return targetObj;
    }

    public override bool CanConvert(Type objectType)
    {
        // CanConvert is not called when [JsonConverter] attribute is used
        return false;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value,
                                   JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

为了进行演示,我们假设JSON现在如下所示:

{
  "name": "Joe Shmoe",
  "age": 26,
  "picture": {
    "id": 123456,
    "data": {
      "type": "jpg",
      "url": "http://www.someplace.com/mypicture.jpg"
    }
  },
  "favorites": {
    "movie": {
      "title": "The Godfather",
      "starring": "Marlon Brando",
      "year": 1972
    },
    "color": "purple"
  }
}

......并且您对此人最喜欢的电影感兴趣(标题和年份)和最喜欢的颜色以及前面的信息。首先用[JsonConverter]属性标记目标类以将其与自定义转换器关联,然后在每个属性上使用[JsonProperty]属性,指定所需的属性路径目标属性也不必是原语--您可以使用一个子类,就像我在这里对Movie所做的那样(请注意,不需要插入Favorites类)。

[JsonConverter(typeof(JsonPathConverter))]
class Person
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("age")]
    public int Age { get; set; }

    [JsonProperty("picture.data.url")]
    public string ProfilePicture { get; set; }

    [JsonProperty("favorites.movie")]
    public Movie FavoriteMovie { get; set; }

    [JsonProperty("favorites.color")]
    public string FavoriteColor { get; set; }
}

// Don't need to mark up these properties because they are covered by the 
// property paths in the Person class
class Movie
{
    public string Title { get; set; }
    public int Year { get; set; }
}

在所有属性就绪后,您可以像平常一样进行反序列化,并且它应该"正常工作":

Person p = JsonConvert.DeserializeObject<Person>(json);

小提琴:https://dotnetfiddle.net/Ljw32O

pxq42qpu

pxq42qpu2#

标记的答案未100%完成,因为它忽略了可能注册的任何IContractResolver,如CamelCasePropertyNamesContractResolver等。
另外,为can convert返回false将防止其他用户案例,因此我将其更改为return objectType.GetCustomAttributes(true).OfType<JsonPathConverter>().Any();
以下是更新后的版本:https://dotnetfiddle.net/F8C8U8
我还删除了在属性上设置JsonProperty的需要,如链接中所示。
如果出于某种原因,上面的链接死亡或爆炸i还包括下面的代码:

public class JsonPathConverter : JsonConverter
    {
        /// <inheritdoc />
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            JObject jo = JObject.Load(reader);
            object targetObj = Activator.CreateInstance(objectType);

            foreach (PropertyInfo prop in objectType.GetProperties().Where(p => p.CanRead && p.CanWrite))
            {
                JsonPropertyAttribute att = prop.GetCustomAttributes(true)
                                                .OfType<JsonPropertyAttribute>()
                                                .FirstOrDefault();

                string jsonPath = att != null ? att.PropertyName : prop.Name;

                if (serializer.ContractResolver is DefaultContractResolver)
                {
                    var resolver = (DefaultContractResolver)serializer.ContractResolver;
                    jsonPath = resolver.GetResolvedPropertyName(jsonPath);
                }

                if (!Regex.IsMatch(jsonPath, @"^[a-zA-Z0-9_.-]+$"))
                {
                    throw new InvalidOperationException($"JProperties of JsonPathConverter can have only letters, numbers, underscores, hiffens and dots but name was ${jsonPath}."); // Array operations not permitted
                }

                JToken token = jo.SelectToken(jsonPath);
                if (token != null && token.Type != JTokenType.Null)
                {
                    object value = token.ToObject(prop.PropertyType, serializer);
                    prop.SetValue(targetObj, value, null);
                }
            }

            return targetObj;
        }

        /// <inheritdoc />
        public override bool CanConvert(Type objectType)
        {
            // CanConvert is not called when [JsonConverter] attribute is used
            return objectType.GetCustomAttributes(true).OfType<JsonPathConverter>().Any();
        }

        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var properties = value.GetType().GetRuntimeProperties().Where(p => p.CanRead && p.CanWrite);
            JObject main = new JObject();
            foreach (PropertyInfo prop in properties)
            {
                JsonPropertyAttribute att = prop.GetCustomAttributes(true)
                    .OfType<JsonPropertyAttribute>()
                    .FirstOrDefault();

                string jsonPath = att != null ? att.PropertyName : prop.Name;

                if (serializer.ContractResolver is DefaultContractResolver)
                {
                    var resolver = (DefaultContractResolver)serializer.ContractResolver;
                    jsonPath = resolver.GetResolvedPropertyName(jsonPath);
                }

                var nesting = jsonPath.Split('.');
                JObject lastLevel = main;

                for (int i = 0; i < nesting.Length; i++)
                {
                    if (i == nesting.Length - 1)
                    {
                        lastLevel[nesting[i]] = new JValue(prop.GetValue(value));
                    }
                    else
                    {
                        if (lastLevel[nesting[i]] == null)
                        {
                            lastLevel[nesting[i]] = new JObject();
                        }

                        lastLevel = (JObject)lastLevel[nesting[i]];
                    }
                }
            }

            serializer.Serialize(writer, main);
        }
    }
pbgvytdp

pbgvytdp3#

而不是做

lastLevel [nesting [i]] = new JValue(prop.GetValue (value));

你必须做

lastLevel[nesting[i]] = JValue.FromObject(jValue);

否则我们有一个
无法确定类型的JSON对象类型...
例外
一段完整的代码如下所示:

object jValue = prop.GetValue(value);
if (prop.PropertyType.IsArray)
{
    if(jValue != null)
        //https://stackoverflow.com/a/20769644/249895
        lastLevel[nesting[i]] = JArray.FromObject(jValue);
}
else
{
    if (prop.PropertyType.IsClass && prop.PropertyType != typeof(System.String))
    {
        if (jValue != null)
            lastLevel[nesting[i]] = JValue.FromObject(jValue);
    }
    else
    {
        lastLevel[nesting[i]] = new JValue(jValue);
    }                               
}
dsf9zpds

dsf9zpds4#

如果有人需要使用@BrianRogers的JsonPathConverter和WriteJson选项,这里有一个解决方案(只适用于带点的路径):
删除CanWrite属性,使其在默认情况下再次变为true
WriteJson代码替换为以下代码:

public override void WriteJson(JsonWriter writer, object value,
    JsonSerializer serializer)
{
    var properties = value.GetType().GetRuntimeProperties ().Where(p => p.CanRead && p.CanWrite);
    JObject main = new JObject ();
    foreach (PropertyInfo prop in properties) {
        JsonPropertyAttribute att = prop.GetCustomAttributes(true)
            .OfType<JsonPropertyAttribute>()
            .FirstOrDefault();

        string jsonPath = (att != null ? att.PropertyName : prop.Name);
        var nesting=jsonPath.Split(new[] { '.' });
        JObject lastLevel = main;
        for (int i = 0; i < nesting.Length; i++) {
            if (i == nesting.Length - 1) {
                lastLevel [nesting [i]] = new JValue(prop.GetValue (value));
            } else {
                if (lastLevel [nesting [i]] == null) {
                    lastLevel [nesting [i]] = new JObject ();
                }
                lastLevel = (JObject)lastLevel [nesting [i]];
            }
        }

    }
    serializer.Serialize (writer, main);
}

正如我上面所说的,这只适用于包含的路径,因此,您应该在ReadJson中添加以下代码以防止其他情况:

[...]
string jsonPath = (att != null ? att.PropertyName : prop.Name);
if (!Regex.IsMatch(jsonPath, @"^[a-zA-Z0-9_.-]+$")) {
    throw new InvalidOperationException("JProperties of JsonPathConverter can have only letters, numbers, underscores, hiffens and dots."); //Array operations not permitted
}
JToken token = jo.SelectToken(jsonPath);
[...]
kse8i1jr

kse8i1jr5#

另一个解决方案(原始源代码取自https://gist.github.com/lucd/cdd57a2602bd975ec0a6)。我清理了源代码并添加了类/类数组支持。需要C#7

/// <summary>
/// Custom converter that allows mapping a JSON value according to a navigation path.
/// </summary>
/// <typeparam name="T">Class which contains nested properties.</typeparam>
public class NestedJsonConverter<T> : JsonConverter
    where T : new()
{
    /// <inheritdoc />
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(T);
    }

    /// <inheritdoc />
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var result = new T();
        var data = JObject.Load(reader);

        // Get all properties of a provided class
        var properties = result
            .GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);

        foreach (var propertyInfo in properties)
        {
            var jsonPropertyAttribute = propertyInfo
                .GetCustomAttributes(false)
                .FirstOrDefault(attribute => attribute is JsonPropertyAttribute);

            // Use either custom JSON property or regular property name
            var propertyName = jsonPropertyAttribute != null
                ? ((JsonPropertyAttribute)jsonPropertyAttribute).PropertyName
                : propertyInfo.Name;

            if (string.IsNullOrEmpty(propertyName))
            {
                continue;
            }

            // Split by the delimiter, and traverse recursively according to the path
            var names = propertyName.Split('/');
            object propertyValue = null;
            JToken token = null;
            for (int i = 0; i < names.Length; i++)
            {
                var name = names[i];
                var isLast = i == names.Length - 1;

                token = token == null
                    ? data.GetValue(name, StringComparison.OrdinalIgnoreCase)
                    : ((JObject)token).GetValue(name, StringComparison.OrdinalIgnoreCase);

                if (token == null)
                {
                    // Silent fail: exit the loop if the specified path was not found
                    break;
                }

                if (token is JValue || token is JArray || (token is JObject && isLast))
                {
                    // simple value / array of items / complex object (only if the last chain)
                    propertyValue = token.ToObject(propertyInfo.PropertyType, serializer);
                }
            }

            if (propertyValue == null)
            {
                continue;
            }

            propertyInfo.SetValue(result, propertyValue);
        }

        return result;
    }

    /// <inheritdoc />
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
    }
}

样品型号

public class SomeModel
{
    public List<string> Records { get; set; }

    [JsonProperty("level1/level2/level3")]
    public string SomeValue{ get; set; }
}

示例json:

{
    "records": ["some value1", "somevalue 2"],
    "level1":
    {
         "level2":
         {
             "level3": "gotcha!"
         }
    }
}

添加JsonConverter后,可以像这样使用它:

var json = "{}"; // input json string
var settings = new JsonSerializerSettings();
settings.Converters.Add(new NestedJsonConverter<SomeModel>());
var result = JsonConvert.DeserializeObject<SomeModel>(json , settings);

小提琴:https://dotnetfiddle.net/pBK9dj
请记住,如果您在不同的类中有多个嵌套属性,则需要添加与您拥有的类一样多的转换器:

settings.Converters.Add(new NestedJsonConverter<Model1>());
settings.Converters.Add(new NestedJsonConverter<Model2>());
...
khbbv19g

khbbv19g6#

顺便说一句,我添加了一些额外的东西来解释嵌套属性上的其他转换。例如,我们有一个嵌套的DateTime?属性,但是结果有时会以空字符串的形式提供,所以我们必须有 * 另一个 * JsonConverter来适应这种情况。
我们班是这样结束的:

[JsonConverter(typeof(JsonPathConverter))] // Reference the nesting class
public class Timesheet {

    [JsonConverter(typeof(InvalidDateConverter))]
    [JsonProperty("time.start")]
    public DateTime? StartTime { get; set; }

}

JSON为:

{
    time: {
        start: " "
    }
}

上述JsonConverter的最终更新为:

var token = jo.SelectToken(jsonPath);
                if (token != null && token.Type != JTokenType.Null)
                {
                    object value = null;

                    // Apply custom converters
                    var converters = prop.GetCustomAttributes<JsonConverterAttribute>(); //(true).OfType<JsonPropertyAttribute>().FirstOrDefault();
                    if (converters != null && converters.Any())
                    {
                        foreach (var converter in converters)
                        {
                            var converterType = (JsonConverter)Activator.CreateInstance(converter.ConverterType);
                            if (!converterType.CanRead) continue;
                            value = converterType.ReadJson(token.CreateReader(), prop.PropertyType, value, serializer);
                        }
                    }
                    else
                    {
                        value = token.ToObject(prop.PropertyType, serializer);
                    }

                    prop.SetValue(targetObj, value, null);
                }
nue99wik

nue99wik7#

在此线程中所有答案的帮助下,我提出了JsonPathConverter类(用作JsonConverter属性)的解决方案,该类实现了ReadJsonWriteJson,并使用正斜杠
类实现:

/// <summary>
/// Custom converter that allows mapping a JSON value according to a navigation path using forward slashes "/".
/// </summary>
public class JsonPathConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject data = JObject.Load(reader);
        object resultObject = Activator.CreateInstance(objectType);

        // Get all properties of a provided class
        PropertyInfo[] properties = objectType
            .GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);

        foreach (PropertyInfo propertyInfo in properties)
        {
            JsonPropertyAttribute propertyAttribute = propertyInfo
                .GetCustomAttributes(true)
                .OfType<JsonPropertyAttribute>()
                .FirstOrDefault();

            // Use either custom JSON property or regular property name
            string propertyJsonPath = propertyAttribute != null
                ? propertyAttribute.PropertyName
                : propertyInfo.Name;

            if (string.IsNullOrEmpty(propertyJsonPath))
            {
                continue;
            }

            // Split by the delimiter, and traverse recursively according to the path
            string[] nesting = propertyJsonPath.Split('/');
            object propertyValue = null;
            JToken token = null;
            for (int i = 0; i < nesting.Length; i++)
            {
                string name = nesting[i];
                bool isLast = i == nesting.Length - 1;

                token = token == null
                    ? data.GetValue(name, StringComparison.OrdinalIgnoreCase)
                    : ((JObject)token).GetValue(name, StringComparison.OrdinalIgnoreCase);

                if (token == null)
                {
                    // Silent fail: exit the loop if the specified path was not found
                    break;
                }

                if (token is JValue || token is JArray || (token is JObject && isLast))
                {
                    // simple value / array of items / complex object (only if the last chain)
                    propertyValue = token.ToObject(propertyInfo.PropertyType, serializer);
                }
            }

            if (propertyValue == null)
            {
                continue;
            }

            propertyInfo.SetValue(resultObject, propertyValue);
        }

        return resultObject;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JObject resultJson = new();

        // Get all properties of a provided class
        IEnumerable<PropertyInfo> properties = value
            .GetType().GetRuntimeProperties().Where(p => p.CanRead && p.CanWrite);

        foreach (PropertyInfo propertyInfo in properties)
        {
            JsonPropertyAttribute propertyAttribute = propertyInfo
                .GetCustomAttributes(true)
                .OfType<JsonPropertyAttribute>()
                .FirstOrDefault();

            // Use either custom JSON property or regular property name
            string propertyJsonPath = propertyAttribute != null
                ? propertyAttribute.PropertyName
                : propertyInfo.Name;

            if (serializer.ContractResolver is DefaultContractResolver resolver)
            {
                propertyJsonPath = resolver.GetResolvedPropertyName(propertyJsonPath);
            }

            if (string.IsNullOrEmpty(propertyJsonPath))
            {
                continue;
            }

            // Split by the delimiter, and traverse according to the path
            string[] nesting = propertyJsonPath.Split('/');
            JObject lastJsonLevel = resultJson;
            for (int i = 0; i < nesting.Length; i++)
            {
                if (i == nesting.Length - 1)
                {
                    lastJsonLevel[nesting[i]] = JToken.FromObject(propertyInfo.GetValue(value));
                }
                else
                {
                    if (lastJsonLevel[nesting[i]] == null)
                    {
                        lastJsonLevel[nesting[i]] = new JObject();
                    }

                    lastJsonLevel = (JObject)lastJsonLevel[nesting[i]];
                }
            }
        }

        serializer.Serialize(writer, resultJson);
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.GetCustomAttributes(true).OfType<JsonPathConverter>().Any();
    }
}

请记住,您还需要以下用法:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System.Reflection;

这个定制的JsonConverter的用法非常简单,假设我们有OP的JSON:

{
    "picture":
    {
        "id": 123456,
        "data":
        {
            "type": "jpg",
            "url": "http://www.someplace.com/mypicture.jpg"
        }
    }
}

据此,我们可以创建保存JSON数据的对象:

[JsonConverter(typeof(JsonPathConverter))]
public class Picture
{
    [JsonProperty("id")]
    public int Id { get; set; }

    [JsonProperty("data/type")]
    public int Type { get; set; }

    [JsonProperty("data/url")]
    public string Url { get; set; }
}

**注意:**不要忘记使用JsonConverter属性标记目标类,并如上所示指定新创建的JsonPathConverter转换器。

然后像往常一样将JSON反序列化为我们的对象:

var picture = JsonConvert.DeserializeObject<Picture>(json);

相关问题