【问题标题】:Why is JsonConvert.DeserializeObject<T> throwing a JsonReaderException?为什么 JsonConvert.DeserializeObject<T> 会抛出 JsonReaderException?
【发布时间】:2017-06-14 13:18:10
【问题描述】:

在我的 Xamarin 表单项目中,我解析从文件加载的 JSON 数据。 无论如何,JSON 数据是 1000% 有效的,因为我可以在其他地方解析它,并且它已经被原生 Android 应用程序 (Java) 和 PHP 使用,没有任何问题,但不知何故 Xamarin 无法理解它,它给了我这个错误:

未处理的异常:

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path 'category', line 1, position 26.

现在这是我的 JSON 数据:

{"response":1,"category":{"2":{"n":"V\u00e9hicules","d":"C-Vehicules","i":"icon-car","l":{"3":{"n":"Voitures","d":"Voitures"},"4":{"n":"Motos","d":"Motos"},"6":{"n":"Nautisme","d":"Nautisme"},"7":{"n":"\u00c9quipement Auto","d":"Equipement-Auto"},"8":{"n":"\u00c9quipement Moto","d":"Equipement-Moto"},"10":{"n":"Equipement Nautisme","d":"Equipement-Nautisme"}}},"3":{"n":"Immobilier","d":"C-Immobilier","i":"icon-office","l":{"15":{"n":"Ventes immobili\u00e8res","d":"Ventes-immobilieres"},"16":{"n":"Locations","d":"Locations"},"17":{"n":"Bureaux - Commerces","d":"Bureaux-Commerces"}}},"1":{"n":"Emploi","d":"C-Emploi","i":"icon-bag","l":{"1":{"n":"Offres d'emploi","d":"Offres-d--emploi"}}},"9":{"n":"Services","d":"C-Services","i":"icon-service","l":{"18":{"n":"Prestations de services","d":"Prestations-de-services"},"19":{"n":"Cours particuliers","d":"Cours-particuliers"}}},"4":{"n":"Vacances","d":"C-Vacances","i":"icon-plane","l":{"20":{"n":"Locations de vacances","d":"Locations-de-vacances"},"21":{"n":"Chambres d'h\u00f4tes","d":"Chambres-d--hotes"},"22":{"n":"Campings","d":"Campings"}}},"7":{"n":"Loisirs","d":"C-Loisirs","i":"icon-music","l":{"24":{"n":"CD Musique","d":"CD-Musique"},"23":{"n":"DVD Films","d":"DVD-Films"},"27":{"n":"Jeux - Jouets","d":"Jeux-Jouets"},"25":{"n":"Livres","d":"Livres"},"26":{"n":"Sports","d":"Sports"}}},"5":{"n":"Maison","d":"C-Maison","i":"icon-house","l":{"36":{"n":"Accessoires","d":"Accessoires"},"28":{"n":"Ameublement","d":"Ameublement"},"30":{"n":"Arts de la table","d":"Arts-de-la-table"},"38":{"n":"B\u00e9b\u00e9","d":"Bebe"},"37":{"n":"Bijoux - Montres","d":"Bijoux-Montres"},"33":{"n":"Bricolage","d":"Bricolage"},"35":{"n":"Chaussures","d":"Chaussures"},"31":{"n":"D\u00e9coration","d":"Decoration"},"29":{"n":"Electrom\u00e9nager","d":"Electromenager"},"32":{"n":"Linge de maison","d":"Linge-de-maison"},"34":{"n":"V\u00eatements","d":"Vetements"}}},"6":{"n":"Multim\u00e9dia","d":"C-Multimedia","i":"icon-phone","l":{"40":{"n":"Consoles - Jeux vid\u00e9o","d":"Consoles-Jeux-video"},"41":{"n":"Image - Son","d":"Image-Son"},"39":{"n":"Informatique","d":"Informatique"},"42":{"n":"T\u00e9l\u00e9phonie","d":"Telephonie"}}},"8":{"n":"Mat\u00e9riel professionnel","d":"C-Materiel-professionnel","i":"icon-tool","l":{"47":{"n":"Equipements","d":"Equipements"},"43":{"n":"Mat\u00e9riel agricole","d":"Materiel-agricole"},"45":{"n":"Mat\u00e9riel BTP","d":"Materiel-BTP"},"46":{"n":"Outillage","d":"Outillage"},"48":{"n":"Restauration - caf\u00e9","d":"Restauration-cafe"},"44":{"n":"Transport","d":"Transport"}}}}}

这是发生异常的那一行:

var general = JsonConvert.DeserializeObject<GeneralConfig>(config);

更新:

我没有放置完整的 JSON 文件,我在上面的示例中通过删除类别旁边的其他对象来简化它,我简化它的原因是因为 SO 不会让放置整个 JSON 内容和错误消息清楚地表明问题出在此处:

 "category":{"2":{"n":"V\u00e9hicules",

更新:

这是读取 JSON 的代码:

namespace HelloWorldApp
{
class Config
{

    string config = "";

    public Config()
    {
        var assembly = typeof(MainPage).GetTypeInfo().Assembly;
        //Stream stream = assembly.GetManifestResourceStream("HelloWorldApp.Resources.configs.json");
        string[] resources = Assembly.GetExecutingAssembly().GetManifestResourceNames();
        foreach (string resource in resources)
        {
            if (resource.EndsWith(".json"))
            {
                Stream stream = assembly.GetManifestResourceStream(resource);
                if (stream != null)
                {
                    using (var reader = new System.IO.StreamReader(stream))
                    {
                        config = reader.ReadToEnd();
                    }
                }
            }
        }

    }

    public void getCategory(int id)
    {
        var general = JsonConvert.DeserializeObject<GeneralConfig>(config);
        var category = general.category;
        var cats = JsonConvert.DeserializeObject<List<CategoryConfig>>(config);
        foreach (var item in cats)
        {
            Console.WriteLine("Cat: " + item.n);
        }
    }

这是常规配置:

class GeneralConfig
{
    public string category { get; set; }
    public int city { get; set; }
    public string brand { get; set; }
    public int model { get; set; }
}

错误 2:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'HelloWorldApp.CategoryConfig' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化的列表。 JsonArrayAttribute 也可以添加到类型中以强制它从 JSON 数组中反序列化。 路径“类别”,第 1 行,位置 26。

【问题讨论】:

  • 我用的是:jsoneditoronline.org,同样的 JSON 在 Java 中被完美解析,我不认为 C# 有它自己的 JSON 规则,或者是这样吗?
  • @GeraldVersluis 奇怪,JSONLint 和 Curious Concept 说它有效。
  • json2csharp 说不
  • 可以,而且没有什么不同的规则。 JSON 错误意味着 string 有问题。至少,这个字符串包含不应该存在的转义序列。没有理由在 Unicode 字符串 中使用转义序列
  • @PanagiotisKanavos JSON 文本中没有转义序列,\u00e 是法语字母 é 的 unicode 翻译

标签: c# json xamarin xamarin.forms


【解决方案1】:

您的类似乎定义不正确。

category 显然不是基于 JSON 数据的字符串。

我认为您需要定义一个容器对象,例如:

public class GeneralConfig
{
    int response;
    Dictionary<string,CategoryConfig> category;
}

另外你应该只打电话给JsonConvert.DeserializeObject&lt;GeneralConfig&gt;(),你不应该打第二个电话。

【讨论】:

  • Category是一个有多个子对象的对象,我应该声明什么类型?
  • 您需要为字典项定义自定义类,然后 GeneralConfig 将需要包含某种 Dictionary 作为成员。
  • 哦,有道理,我有一个 Category 对象,让我试着回来,1 分钟。
  • 我认为这是正确的道路,但它给了我这个错误:(见更新的问题)
  • 您需要更好地了解进入应用程序的数据的结构。如果您此时无法使其工作,我会考虑制作一个 MCVE
【解决方案2】:

嗯,首先,您已经回答了自己的问题。 Xamarin 是一个运行时,它如何或为什么需要“理解”JSON?

问题来自Newtonsoft.Json.JsonReaderException。如异常消息所示,您的 JSON 无效。

问题绝对是第 26 位的 Unicode 符号V\u00e9hicules

这个答案应该会有所帮助:Serializing foreign languages using JSON.Net

【讨论】:

  • 那根本不是 Unicode 符号。 OP 没有发布 actual 字符串,这使得解决问题相当困难
  • @PanagiotisKanavos 那是实际数据只是稍微简化了一点,好吧,我会发布完整的 JSON,我想这与错误无关。
  • Unicode 字符串没有转义序列。您可以在 .NET 字符串中输入 :'Véhicules' 就可以了
  • @user9993 在文本的第 26 位是{"2",所以我认为您根本没有走在正确的轨道上。
【解决方案3】:

C# 没有以数字开头的属性。例如,"2": 不能反序列化为属性。

而且你的 json 在很多地方都有转义字符 `\u00',也许这也是一个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2021-03-05
    • 2021-03-19
    • 2023-03-14
    • 1970-01-01
    • 2021-04-09
    相关资源
    最近更新 更多