反序列化JSon对象错误 [英] Deserialize JSon Object error

查看:294
本文介绍了反序列化JSon对象错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要反序列化Json Object的帮助.这是我写的代码,

Hi I need your help for Deserialize Json Object. This is The code I wrote,

String s = File.ReadAllText(@"C:\Users\User\Desktop/json1.json");
var myfields = Newtonsoft.Json.JsonConvert.DeserializeObject<YourTwoField>(s);
Console.WriteLine(myfields.FieldOne);

这是JSON OBJECT的类

and this is the class for the JSON OBJECT

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;


public class YourTwoField
{
    [JsonProperty("brand_name")]
    public List<string> FieldOne { get; set; }

    [JsonProperty("generic_name")]
    public List<string> FieldTwo { get; set; }
}

仍然不起作用,出现错误:

and still It doesnt working, I'm getting the error:

Newtonsoft.Json.dll中发生了类型为'Newtonsoft.Json.JsonReaderException'的未处理异常.

An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll.

这是JSON结果:链接

谢谢

推荐答案

json包含结果的列表,该结果包含openfda属性.就像openfda一样,它可以包含一个以上的brand_namegeneric_name.

The json contains a list of results that contain a openfda property. As wel as a openfda that can contain more then one brand_name and generic_name.

因为您只要求获得这两个属性,所以我的示例仅基于这两个属性.

Because you are asking to only get these two properties, my example is based on only those two.

课程:

public class Openfda
{     
    [JsonProperty("generic_name")]
    public List<string> GenericName { get; set; }

    [JsonProperty("brand_name")]
    public List<string> BrandName { get; set; }     
}

public class Result
{
    [JsonProperty("openfda")]
    public Openfda Openfda { get; set; }   
}

public class Root
{
    [JsonProperty("results")]
    public List<Result> Results { get; set; }
}

反序列化:

var myfields = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(json);

Console.WriteLine(myfields.Results[0].Openfda.BrandName[0]);
Console.WriteLine(myfields.Results[0].Openfda.GenericName[0]);


dynamic方式(无强类型属性):

The dynamic way (without strong typed properties):

dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

Console.WriteLine(obj.results[0].openfda.brand_name[0]);
Console.WriteLine(obj.results[0].openfda.generic_name[0]);

这篇关于反序列化JSon对象错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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