SQL Server Expected a value of type 'String', but got one of type 'List< dynamic>'

x33g5p2x  于 2023-06-21  发布在  Go
关注(0)|答案(3)|浏览(168)

I want integrate Flutter with an ASP.NET API. the problem is when I create minimal API, the JSON I retrieved from MapGet is a string , when I try to jsondecode() it give me:
Expected a value of type 'String', but got one of type 'List'

This is my code

void main() async {
  final dio = Dio();
  final response = await dio.get('https://localhost:7169/Result');
  print(response.data);
  
  var json = jsonDecode(response.data);

  // Access the JSON values
  String name = json['Drainage_ID'];
  int age = json['date'];

  // Print the values
  print('id: $name');
  print('tarikh: $age');
}

The data was in supposed to be JSON but it comes in a format like this

[
string
string
]

This is my GET in my minimal API

app.MapGet("/Result", () =>
{
    var rows = new List<string>();
    using var conn = new SqlConnection(connectionString);
    StringBuilder errorMessages = new StringBuilder();
    conn.Open();
    String query =
        "SELECT TOP 100 A.DR_PI_000_01 AS drainage_id,MAX(A.DR_PI_000_03) AS latest_time " +
        "\r\nFROM DR_PI_000 A\r\n\r\nGROUP BY A.DR_PI_000_01";
    try
    {
        var command = new SqlCommand(query, conn);
        command.CommandTimeout = 1000;
        using SqlDataReader reader = command.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader!.Read())
            {
                rows.Add($"'Drainage_ID': '{(reader.IsDBNull(0) ? null : reader?.GetString(0))}','date':'{(reader!.IsDBNull(1) ? null : reader?.GetDateTime(1))}',");
                
            }
        }
        // …
    }
    catch (SqlException se)
    {
        for (int i = 0; i < se.Errors.Count; i++)
        {
            errorMessages.Append("Index #" + i + "\n" +
                "Message: " + se.Errors[i].Message + "\n" +
                "LineNumber: " + se.Errors[i].LineNumber + "\n" +
                "Source: " + se.Errors[i].Source + "\n" +
                "Procedure: " + se.Errors[i].Procedure + "\n");
        }
        Console.WriteLine(errorMessages.ToString());

    }

    return rows;
})
.WithName("GetResult");

How to solve this error? Do I need to loop somewhere in flutter?

EDIT: this my response body from swagger Map GET

[
  "'Drainage_ID': 'DR/C1/IC/H/-/GPG/PU/-/RCP/01','date':'10/5/2022 12:00:00 AM',",
  "'Drainage_ID': 'DR/C1/IC/H/-/GPG/PU/-/RCP/02','date':'10/5/2022 12:00:00 AM',",
  "'Drainage_ID': 'DR/C1/IC/H/-/GPG/SP/-/RCP/01','date':'10/5/2022 12:00:00 AM',",
  "'Drainage_ID': 'DR/C1/IC/H/-/GPG/UP/-/RCP/02','date':'9/24/2003 12:00:00 AM',",
  "'Drainage_ID': 'DR/C1/IC/H/-/GPG/UP/-/RCP/01','date':'10/5/2022 12:00:00 AM',",
  "'Drainage_ID': 'DR/C1/IC/H/-/SPP/PU/-/RCP/01','date':'10/5/2022 12:00:00 AM',",
  "'Drainage_ID': 'DR/C1/IC/H/-/SPP/PU/-/RCP/02','date':'8/30/2005 12:00:00 AM',",
  "'Drainage_ID': 'DR/C1/IC/H/-/SPP/UP/-/RCP/02','date':'10/12/2022 12:00:00 AM',",
]

noted when i post this on POSTMAN, it get result as String instead of json

ttisahbt

ttisahbt1#

You should not use jsonDecode with response.data because Dio already does it for you.

final dio = Dio();
  final response = await dio.get('https://localhost:7169/Result');
  print(response.data);
  // if you are sure response is List
  final list = response.data as List<dynamic>;
  // use list
tag5nh1u

tag5nh1u2#

This is how I work with JSON data.

final dio = Dio();
List? value;
@override
void initState() {
// TODO: implement initState
super.initState();
getHttp();
}
void getHttp() async {
final response =
    await dio.get('https://jsonplaceholder.typicode.com/posts/');
value = response.data as List;
}
mi7gmzs6

mi7gmzs63#

I see schema issues in your json content; you could use a json validator like https://jsonlint.com/ .

json content may be in two formats, array of objects ie [{},{}] and object ie {} with double quoted properties and values (other than number, boolean and object); see the above link for details.

you can rewrite these lines of your endpoint to create correct format, like:

while (reader!.Read())
{
    rows.Add($"{{\"Drainage_ID\": \"{(reader.IsDBNull(0) ? null : reader?.GetString(0))}\",\"date\":\"{(reader!.IsDBNull(1) ? null : reader?.GetDateTime(1))}\"}}");
            
}

相关问题