gpt4 book ai didi

C#通过ID访问JSON内容

转载 作者:行者123 更新时间:2023-11-30 16:05:11 26 4
gpt4 key购买 nike

所以我需要从我的 C# 项目中解析一个 JSON 字符串。我将 JSON 作为方法调用的响应,json 如下所示:

{
"10": {
"entity_id": "10",
"attribute_set_id": "4",
"type_id": "simple",
"sku": "convertor-touchscreen",
"name": "Convertor touchscreen",
"meta_title": null,
"meta_description": null,
"url_key": "convertor-touchscreen",
"custom_design": null,
"page_layout": null,
"options_container": "container1",
"country_of_manufacture": null,
"msrp_enabled": "2",
"msrp_display_actual_price_type": "4",
"gift_message_available": null,
"creareseo_discontinued": null,
"creareseo_discontinued_product": null,
"description": "Convertor touchscreen",
"short_description": "Convertor touchscreen",
"meta_keyword": null,
"custom_layout_update": null,
"price": "421.0000",
"special_price": "380.0000",
"weight": "0.1500",
"msrp": null,
"special_from_date": "2015-11-24 00:00:00",
"special_to_date": "2015-11-26 00:00:00",
"news_from_date": null,
"news_to_date": null,
"custom_design_from": null,
"custom_design_to": null,
"status": "1",
"visibility": "4",
"tax_class_id": "2",
"featured": "1"
}
}

所以我需要访问诸如“entity_id”、“name”等成员...所以我试过了

using Newtonsoft.Json.Linq;
...
// output is the above JSON string
var jo = JObject.Parse(output);
var id = jo[0]["entity_id"].ToString();

但显然这不是一个好办法。另外,我无法控制第一部分

{
"10": {

所以我做不到

var id = jo["10"]["entity_id"].ToString();

因为我不知道下一个 JSON 字符串中的值“10”是什么。那么如何通过 Id 或其他方式获取元素值呢?

最佳答案

如果您事先不知道 10 的值,很明显您无法使用此键访问其内容(在您的示例中,这将是访问其他属性的键)。如果此对象始终具有 1 个顶级属性,那么您的代码就可以了:

var jo = JObject.Parse(output);
var id = jo[0]["entity_id"].ToString();

在尝试访问 jo 数组之前,添加一些防御性检查以确保它至少具有一个属性。

另一方面,如果 key 位于您所知道的实体的某些属性内,那么可以随意遍历 jo 的所有顶级属性> 变量检查子属性以获取您知道的键的值,直到找到所需的记录。

关于C#通过ID访问JSON内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33984327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com