【发布时间】:2019-04-16 01:48:34
【问题描述】:
尝试解析 JSON 文件时,我收到错误“JsonPropertyAttribute”由于其保护级别而无法访问。 应该修改什么以消除此错误?
我尝试为 JsonProperty 添加一个公共构造函数,但它导致了另一个错误,即 JsonProperty 不是属性类。
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace NordstromRack
{
public partial class ReadJson
{
[JsonProperty("items")]
public Item[] Items { get; set; }
}
public partial class Item
{
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("item_xpath", NullValueHandling = NullValueHandling.Ignore)]
public string ItemXpath { get; set; }
[JsonProperty("item_size")]
public string ItemSize { get; set; }
}
public partial class ReadJson
{
public static ReadJson FromJson(string json) => JsonConvert.DeserializeObject<ReadJson>(json, QuickType.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this ReadJson self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
以下是 JSON 文件
{
"items": [{
"url": "https://www.nordstromrack.com/shop/Women/Clothing/Activewear/Jackets%20&%20Hoodies",
"item_xpath": "//*[@href='/shop/product/2299794/nike-vintage-drawstring-hoodie?color=BLACK%2FSAIL']",
"item_size": "//*[@href='?color=TRUBER%2FSAIL&size=L']"
},
{
"url": "https://www.nordstromrack.com/shop/product/2843153/blu-pepper-leopard-tie-sleeve-dress?color=LAVENDER",
"item_size": "//*[@href='?color=LAVENDER&size=L']"
},
{
"url": "https://www.nordstromrack.com/events/281375/products/2584102/j-crew-cotton-cardigan?color=BLACK",
"item_xpath": "//*[@href='/events/281375/products/2584102/j-crew-cotton-cardigan?color=BLACK']",
"item_size": "//*[@href='?color=BLACK&size=M']"
}
]
}
【问题讨论】:
-
在您的other question 中有
public class JsonProperty { }。摆脱它,而是在您的 c# 代码中执行using Newtonsoft.Json;。见:newtonsoft.com/json/help/html/… -
谢谢@dbc。我复制了完全相同的代码,您在我的other question 中修复了编译,但我仍然看到错误'JsonProperty' is not and attribute class。 JsonSerializerSettings、JsonConvert、DateParseHandling、NullValueHandling 的错误相同。
-
那么您可能需要添加对 Json.NET 的引用,请参阅JSON.NET How To Reference?。 why cant i add the newtonsoft.Json.dll ref to my project? 和 How to import JsonConvert in C# application? 也可能有帮助。
-
有效的是通过 NuGet 包安装 Newtonsoft.json。显然即使它没有安装它仍然可以作为一个包导入,但需要安装。
-
很高兴您的问题得到解决。 JSON.NET How To Reference? 和 How to import JsonConvert in C# application? 的重复呢?