简体   繁体   中英

How to parse JSON object into a list of objects in C#

our organization recently changed its database from sqlserver to elasticsearch and I am about creating an application for that, I could successfully create an index and populated that with some information but when I retrieve the information, it returns me the data I really want plus lots of metadata which I don't really need in this context, now my question is how to extract the exact data I need and how to store it in a list, it is the response from the当我按下搜索索引时,响应将是这样的,它是一个 JSON 对象 server when I press the search index button

but I am interested in information that comes exactly after the second "hits" especially I want to extract "_id", "Firstname", "Lastname" and store it in a generic list of the type person which has the corresponding fields. and it is the code in the code-behind file编写在代码隐藏文件中的代码

Copy an example JSON response to your clipboard and generate some Json classes either by:

a. In Visual Studio select Edit / Paste Special / Paste JSON As Classes

b. If your data is not sensitive / you can clean it, use an online site such as http://json2csharp.com

Then deserialize from the Root object.

using var stream = new MemoryStream(data);
using var reader = new StreamReader(stream, Encoding.UTF8);
using var jsonReader = new JsonTextReader(reader);

var json = JsonSerializer.Create().Deserialize<Rootobject>(jsonReader);

Then take the bit you need.

var response = json.hits.hits;

You can further optimise the process by scrubbing all properties on the outer objects that you don't want to deserialize into.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM