我正在嘗試從 c# 中的 json 陣列中獲取第一個物件。陣列看起來像這樣:
[
{
"name": "Joe",
"id": 1
},
{
"name": "Melinda"
"id": 2
}
]
我沒有找到合適的方法來做到這一點,所以我在這里問。我正在使用 System.Text.JSON。我目前正在使用此代碼:
class Program
{
public static void Main(String[] args)
{
HttpClient client = new HttpClient();
string url = "example.com";
string json = client.GetStringAsync(url).ToString()!;
Sensor sensor = JsonSerializer.Deserialize<Sensor>(json)!;
Console.WriteLine(sensor.id);
}
}
public class Sensor
{
public string? id { get; set; }
}
現在,不出所料,當我運行此代碼時,System.Text.Json 會拋出一個錯誤,但我無法破譯究竟是什么原因造成的(prbl bc 我很愚蠢):
inner exception System.Text.Json.JsonReaderException: 'S' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
at System.Text.Json.Utf8JsonReader.Read()
at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
有沒有一種簡單的方法可以使用 System.Text.Json 或 Newtonsoft.Json 做到這一點?謝謝
uj5u.com熱心網友回復:
您應該將 json 字串反序列化為 new List(),然后您可以使用 FirstOrDefault() 方法找到串列的第一個元素,如下所示:
class Sensor
{
public int Id { get; set; }
public string Name { get; set; }
}
public Sensor GetFirstElementOfJsonArray(String data)
{
JsonSerializerOptions options = new JsonSerializerOptions(){
PropertyNameCaseInsensitive = true };
List<Sensor> sensorList=JsonConvert.Deserialize<List<Sensor>>(data,options);
return sensorList.FirstOrDefault();
}
我想,它會回答你的問題
uj5u.com熱心網友回復:
一種非常接近您的方法:
using System;
using System.Text.Json;
public class Program
{
public static readonly string data = @"[{""name"": ""Joe"",""id"": 1},{""name"": ""Melinda"", ""id"": 2 }]";
public static void Main()
{
// System.Text.Json defaults to case-sensitive property matching,
// so I need to switch this to insesitive, if the model adheres
// to C# naming convention ( Props start with capital letter)
JsonSerializerOptions jso = new JsonSerializerOptions(){ PropertyNameCaseInsensitive = true };
// We are deserializing an Array vv
var sensors = JsonSerializer.Deserialize<Sensor[]>(data, jso);
// I do an output for demonstration purposes.
// You'd want to check for null and size>0 and then use the first element.
foreach( var sensor in sensors )
{
Console.WriteLine($"{sensor.Id:#0} : {sensor.Name}");
}
}
}
public class Sensor
{
public int Id {get; set;}
public string Name {get; set;}
}
查看實際操作:https ://dotnetfiddle.net/t7Dkh8
另一個想法是增量決議,如果陣列很長并且您只需要第一個元素,這是有益的。
請參閱C# 中的增量 JSON 決議 (但需要 NewtonSoft)
我和 Jon Skeet 已經在評論中發表了另一句話:
您收到的錯誤訊息
'S' 是一個無效的值開始。行號:0 ...
提示接收到的字串實際上可能不是有效的 json。因此,您可能也想對此進行調查。
您可以設定一個斷點并使用除錯器查看該值,只需將其輸出到文本檔案中,或者如果您有日志記錄,請將其記錄下來。
uj5u.com熱心網友回復:
你需要反序列化到一個類:
public class Sensor {
public int Id { get; set; }
public string Name { get; set; }
}
JsonSerializer.Deserialize<Sensor>(json)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/476518.html
標籤:C# json 。网 system.text.json
上一篇:使用正則運算式,捕獲數字組的最佳方法是什么,忽略其中的任何空格
下一篇:如何設定屬性物件的初始化順序?
