反序列化JSon对象错误 [英] Deserialize JSon Object error
问题描述
我需要反序列化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_name
和generic_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屋!