如何将获取的API数据映射到JSON对象以进行循环
我有以下工作代码从Azure API获取JSON数据:
@code {
string responseBody;
protected override async Task OnInitializedAsync()
{
var personalaccesstoken = "*******";
var uri = "https://dev.azure.com/*****";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalaccesstoken))));
HttpResponseMessage response = client.GetAsync(uri).Result;
response.EnsureSuccessStatusCode();
responseBody = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.Print(">>> responseBody" + responseBody);
}
}
}
我可以在控制台中看到JSON对象,因此上述代码没有问题。 作为参考,这是我看到的输出的一部分。
{
"count": 50,
"value": [
{
"_links": {
"self": {
"href": "https://dev.azure.com/****"
}
}
....
}
}
不幸的是,在C#中,不可能对此响应进行操作,因此在阅读了一点之后,我意识到我需要为响应对象上一堂课才能循环通过它。
@code {
public class BuildItem
{
public string count { get; set; }
public List<Build> builds { get; set; }
}
public class Build
{
public int id { get; set; }
public string _links { get; set; }
public string tags { get; set; }
public string plans { get; set; }
public string queueTime { get; set; }
}
接下来,我将此行添加到@Code {}
block的底部,
BuildItem data = JsonConvert.DeserializeObject<BuildItem>(responseBody);
foreach (var res in data.builds)
{
Console.WriteLine($"Id: {res._links}");
}
我希望只能看到每个链接或仅在list上_links
json的一部分,而是我得到此错误:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
MyBuilds.Components.Builds.BuildItem.builds.get returned null.
感谢您的帮助
**更新:完整的JSON对象**
我唯一需要的是_links
,id> id
build> buildnumber < /code>和状态
{
"count":2,
"value":[
{
"_links":{
"self":{
"href":"****"
},
"web":{
"href":"****"
},
"sourceVersionDisplayUri":{
"href":"****"
},
"timeline":{
"href":"****"
},
"badge":{
"href":"****"
}
},
"properties":{
},
"tags":[
],
"validationResults":[
],
"plans":[
{
"planId":"****"
}
],
"triggerInfo":{
"pr.number":"11244",
"pr.isFork":"False",
"pr.triggerRepository":"****",
"pr.triggerRepository.Type":"TfsGit"
},
"id":106479,
"buildNumber":"****",
"status":"****",
"result":"****",
"queueTime":"****",
"startTime":"****",
"finishTime":"****",
"url":"****",
"definition":{
"drafts":[
],
"id":554,
"name":"****",
"url":"****",
"uri":"****",
"path":"****",
"type":"****",
"queueStatus":"****",
"revision":7,
"project":{
"id":"****",
"name":"****",
"url":"****",
"state":"****",
"revision":****,
"visibility":"****",
"lastUpdateTime":"****"
}
},
"buildNumberRevision":5,
"project":{
"id":"****",
"name":"****",
"url":"****",
"state":"wellFormed",
"revision":749,
"visibility":"private",
"lastUpdateTime":"****"
},
"uri":"****",
"sourceBranch":"****",
"sourceVersion":"****",
"queue":{
"id":313,
"name":"Azure Pipelines",
"pool":{
"id":36,
"name":"Azure Pipelines",
"isHosted":true
}
},
"priority":"normal",
"reason":"pullRequest",
"requestedFor":{
"displayName":"****",
"url":"****",
"_links":{
"avatar":{
"href":"****"
}
},
"id":"****",
"uniqueName":"****",
"imageUrl":"****",
"descriptor":"****"
},
"requestedBy":{
"displayName":"****",
"url":"****",
"_links":{
"avatar":{
"href":"****"
}
},
"id":"****",
"uniqueName":"****",
"imageUrl":"****",
"descriptor":"****"
},
"lastChangedDate":"****",
"lastChangedBy":{
"displayName":"****",
"url":"****",
"_links":{
"avatar":{
"href":"****"
}
},
"id":"****",
"uniqueName":"****",
"imageUrl":"****",
"descriptor":"****"
},
"parameters":"{}",
"orchestrationPlan":{
"planId":"****"
},
"logs":{
"id":0,
"type":"Container",
"url":"****"
},
"repository":{
"id":"****",
"type":"****",
"clean":null,
"checkoutSubmodules":false
},
"keepForever":true,
"retainedByRelease":false,
"triggeredByBuild":null
}
]
}
非常感谢
I have the following working code that fetches a JSON data from Azure API:
@code {
string responseBody;
protected override async Task OnInitializedAsync()
{
var personalaccesstoken = "*******";
var uri = "https://dev.azure.com/*****";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalaccesstoken))));
HttpResponseMessage response = client.GetAsync(uri).Result;
response.EnsureSuccessStatusCode();
responseBody = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.Print(">>> responseBody" + responseBody);
}
}
}
I can see the JSON object in the console, so there is no issue with the above code.
For reference, this is the a portion of the output I see.
{
"count": 50,
"value": [
{
"_links": {
"self": {
"href": "https://dev.azure.com/****"
}
}
....
}
}
Unfortunately, in C# it is not possible to do foreach on this response so after reading a little I realized I need to make a class for the response object in order to loop through it.
@code {
public class BuildItem
{
public string count { get; set; }
public List<Build> builds { get; set; }
}
public class Build
{
public int id { get; set; }
public string _links { get; set; }
public string tags { get; set; }
public string plans { get; set; }
public string queueTime { get; set; }
}
Next, I added added this line to bottom of the @code{}
block
BuildItem data = JsonConvert.DeserializeObject<BuildItem>(responseBody);
foreach (var res in data.builds)
{
Console.WriteLine(quot;Id: {res._links}");
}
I am expecting to see each link or at list only the _links
part of the JSON, but instead I get this error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
MyBuilds.Components.Builds.BuildItem.builds.get returned null.
Thanks for the help
**Update: Full JSON object **
The only ones I need are _links
, id
, buildNumber
and status
{
"count":2,
"value":[
{
"_links":{
"self":{
"href":"****"
},
"web":{
"href":"****"
},
"sourceVersionDisplayUri":{
"href":"****"
},
"timeline":{
"href":"****"
},
"badge":{
"href":"****"
}
},
"properties":{
},
"tags":[
],
"validationResults":[
],
"plans":[
{
"planId":"****"
}
],
"triggerInfo":{
"pr.number":"11244",
"pr.isFork":"False",
"pr.triggerRepository":"****",
"pr.triggerRepository.Type":"TfsGit"
},
"id":106479,
"buildNumber":"****",
"status":"****",
"result":"****",
"queueTime":"****",
"startTime":"****",
"finishTime":"****",
"url":"****",
"definition":{
"drafts":[
],
"id":554,
"name":"****",
"url":"****",
"uri":"****",
"path":"****",
"type":"****",
"queueStatus":"****",
"revision":7,
"project":{
"id":"****",
"name":"****",
"url":"****",
"state":"****",
"revision":****,
"visibility":"****",
"lastUpdateTime":"****"
}
},
"buildNumberRevision":5,
"project":{
"id":"****",
"name":"****",
"url":"****",
"state":"wellFormed",
"revision":749,
"visibility":"private",
"lastUpdateTime":"****"
},
"uri":"****",
"sourceBranch":"****",
"sourceVersion":"****",
"queue":{
"id":313,
"name":"Azure Pipelines",
"pool":{
"id":36,
"name":"Azure Pipelines",
"isHosted":true
}
},
"priority":"normal",
"reason":"pullRequest",
"requestedFor":{
"displayName":"****",
"url":"****",
"_links":{
"avatar":{
"href":"****"
}
},
"id":"****",
"uniqueName":"****",
"imageUrl":"****",
"descriptor":"****"
},
"requestedBy":{
"displayName":"****",
"url":"****",
"_links":{
"avatar":{
"href":"****"
}
},
"id":"****",
"uniqueName":"****",
"imageUrl":"****",
"descriptor":"****"
},
"lastChangedDate":"****",
"lastChangedBy":{
"displayName":"****",
"url":"****",
"_links":{
"avatar":{
"href":"****"
}
},
"id":"****",
"uniqueName":"****",
"imageUrl":"****",
"descriptor":"****"
},
"parameters":"{}",
"orchestrationPlan":{
"planId":"****"
},
"logs":{
"id":0,
"type":"Container",
"url":"****"
},
"repository":{
"id":"****",
"type":"****",
"clean":null,
"checkoutSubmodules":false
},
"keepForever":true,
"retainedByRelease":false,
"triggeredByBuild":null
}
]
}
Thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试以下尝试:
您的JSON字符串具有
value
作为数组/列表,但您的属性名称是您创建的构建的,请尝试将builds
更改为value> value
同样,对于_links,_links也是一个对象,并且您已经创建了字符串,因此您还需要使用其中的属性为_link创建一个类。然后,
self
属性也是一个objec,因此您需要在c#中为JSON String创建模型时,还需要谨慎地创建类。 C#型号将遵循骆驼盒属性名称。
try below:
your JSON string has
value
as array/list but your properties' name is builds that you have created try changing thebuilds
tovalue
also for the _links, so _links is also a object and you have created it string, so you need create a class for the _links as well with the properties in it. then also
self
property is also a objec, so you need to create class with property for that as wellbe careful while creating model for JSON string in C#. C# model will follow the camel case property name.
您的模型:
请求之后:
Your models:
After requesting:
而不是
尝试做
Instead of
Try doing
处理JSON对象时的第一步是确保您正确地映射了C#对象结构和命名法与JSON对象结构和命名法之间。
这是您的原始简单JSON,也是用于将其放入测试页面的对象。找出映射的一种方法是制作一个对象实例并序列化,以便您可以比较两者。您可以看到这是代码。
拥有C#对象后,您可以做任何想要的迭代。
Step one when dealing with Json objects is to make sure you are correctly mapping between your C# object structure and nomenclature and your Json object structure and nomenclature.
Here's your original simpler json and the objects set used to deserialize it put into a test page. One way to figure out your mappings is to make an instance of object and serialize it so you can compare the two. You can see this is the code.
Once you have your C# object you can do whatever iterations you want.