JSON转对象失败:无法反序列化为List,求助解析textlocal.in API结果
Looks like you're hitting a classic mismatch between the JSON structure returned by Textlocal's API and the .NET type you're trying to deserialize it into. Let's break this down and fix it:
Root Cause of the Error
The error message Cannot deserialize the current JSON object into System.Collections.Generic.List tells us exactly what's wrong:
- The API returns a single top-level JSON object (wrapped in
{}), not an array of objects (which would be wrapped in[]). - Your code is trying to deserialize this single object into a collection type (like
List<T>), which the serializer can't do.
Step 1: Create a .NET Class Matching the JSON Structure
First, you need a class that mirrors every field in the JSON response. You can generate this automatically in Visual Studio by copying your JSON, then going to Edit > Paste Special > Paste JSON as Classes. Here's the resulting class structure for your response:
public class TextlocalResponse { public Warning[] warnings { get; set; } public int balance { get; set; } public int batch_id { get; set; } public int cost { get; set; } public int num_messages { get; set; } public MessageDetails message { get; set; } public string receipt_url { get; set; } public string custom { get; set; } public string[] inDND { get; set; } public SentMessage[] messages { get; set; } public string status { get; set; } } public class Warning { public string message { get; set; } public string numbers { get; set; } } public class MessageDetails { public int num_parts { get; set; } public string sender { get; set; } public string content { get; set; } } public class SentMessage { public string id { get; set; } public long recipient { get; set; } }
Step 2: Deserialize to the Single Class Instance (Not a List)
Replace your code that tries to deserialize into a List<T> with code that targets the single TextlocalResponse class. Using Newtonsoft.Json (the most common JSON library for .NET), your code would look like this:
using Newtonsoft.Json; // Assume 'apiResponse' is the raw JSON string you get from Textlocal's API string apiResponse = "{ ... your full JSON response ... }"; try { TextlocalResponse response = JsonConvert.DeserializeObject<TextlocalResponse>(apiResponse); // Now you can access all properties safely Console.WriteLine($"Remaining balance: {response.balance}"); Console.WriteLine($"Status: {response.status}"); } catch (Exception ex) { // Handle any unexpected errors Console.WriteLine($"Deserialization failed: {ex.Message}"); }
Why This Works
By targeting the single class instead of a list, you're matching the structure of the JSON exactly. The serializer can now map each JSON field to the corresponding property in your class without confusion.
内容的提问来源于stack exchange,提问作者Durgesh Padha

