Flutter: How to convert a List to JSON - json

I am trying to convert a list to Json and sent this json to DB.
My list is as following
List<DeviceInfo> deviceInfoList = [];
class DeviceInfo {
final String platform;
final String deviceModel;
final bool isPhysicalDevice;
final String deviceId;
final String imei;
final String meid;
final String platformVersion;
final String projectVersion;
final String projectCode;
final String projectAppID;
final String projectName;
DeviceInfo(
{this.platform,
this.platformVersion,
this.deviceModel,
this.isPhysicalDevice,
this.deviceId,
this.imei,
this.meid,
this.projectVersion,
this.projectCode,
this.projectAppID,
this.projectName});
}
My list contain String and boolean, I had go through this example don't know how to Map string and bool in that map function.
Can anyone help me with this?

Map<String,dynamic> toJson(){
return {
"name": this.name,
"number": this.number,
"surname": this.surname,
};
}
static List encondeToJson(List<DeviceInfo>list){
List jsonList = List();
list.map((item)=>
jsonList.add(item.toJson())
).toList();
return jsonList;
}
List jsonList = Device.encondeToJson(deviceInfoList);
print("jsonList: ${jsonList}");
Is the most short way that I remember.

Couple of options that will help encoding and decoding from JSON: the json_serializable package is a great way to have the boilerplate serialize/deserialize code generated for you. There's examples of how to use this (and built_value, which is powerful, but more complicated to use) in the Flutter samples repo.

Related

Trying to get city name from json but getting null return

I am new to dart and following a this post to get my data from json:
https://medium.com/flutter-community/converting-json-into-class-objects-in-dart-abcc3cc05478
I am getting weather data from api source which gives me to much info. I only want city name first, then onto try get current temp of that city, i pass into api.
i using https://jsonformatter.org/json-to-dart to format into classes.
I just trying to get city name first from json. but getting null return. It is due to City is a MAP???
name = city
i am getting all the data back with 200 response
jsonclass.dart
code:import 'dart:convert';
import 'package:http/http.dart' as http;
import 'apikey.dart';
import 'jasonclasscity.dart';
class WeatherApiException implements Exception {
const WeatherApiException(this.message);
final String message;
}
void main() async {
String url =
'https://api.openweathermap.org/data/2.5/forecast?q=Palm%20Springs&units=imperial';
final httpUrl = Uri.parse('$url$appid');
final response = await http.get(httpUrl);
if (response.statusCode != 200) {
print(response.statusCode);
throw WeatherApiException('Error getting city: xxxxx');
}
print(response.statusCode);
var body = response.body;
print(response.body);
City city = City.fromJson(jsonDecode(body.toString()));
print(city.toString());
}
jsonclasscity.dart
class City {
// final int id;
final String name; //need this
// final Coord coord;
// final String country;
// final int population;
// final int timezone;
// final int sunrise;
// final int sunset;
City(
{
// required this.id,
required this.name
//required this.coord,
//required this.country,
//required this.population,
//required this.timezone,
//required this.sunrise,
//required this.sunset,
});
factory City.fromJson(Map<String, dynamic> json) {
return City(
name: json ["name"],
); // City
}
}
class Coord {
final double lat;
final double lon;
Coord({
required this.lat,
required this.lon,
});
}
class MainClass {
MainClass({
required this.temp, //need this
required this.feelsLike,
required this.tempMin,
required this.tempMax,
required this.pressure,
required this.seaLevel,
required this.grndLevel,
required this.humidity,
required this.tempKf,
});
final double temp;
final double feelsLike;
final double tempMin;
final double tempMax;
final int pressure;
final int seaLevel;
final int grndLevel;
final int humidity;
final double tempKf;
}
json api data back from call:
{"cod":"200","message":0,"cnt":40,"list":[{"dt":1662498000,"main":{"temp":107.73,"feels_like":106.95,"temp_min":107.73,"temp_max":110.3,"pressure":1009,"sea_level":1009,"grnd_level":995,"humidity":18,"temp_kf":-1.43},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"clouds":{"all":0},"wind":{"speed":8.03,"deg":123,"gust":8.99},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-06 21:00:00"},{"dt":1662508800,"main":{"temp":108.37,"feels_like":107.17,"temp_min":108.37,"temp_max":109.33,"pressure":1009,"sea_level":1009,"grnd_level":994,"humidity":17,"temp_kf":-0.53},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"clouds":{"all":1},"wind":{"speed":7.38,"deg":129,"gust":6.78},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-07 00:00:00"},{"dt":1662519600,"main":{"temp":99.99,"feels_like":99.14,"temp_min":99.99,"temp_max":99.99,"pressure":1011,"sea_level":1011,"grnd_level":995,"humidity":24,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":4},"wind":{"speed":0.94,"deg":283,"gust":4.56},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-07 03:00:00"},{"dt":1662530400,"main":{"temp":95.72,"feels_like":95.07,"temp_min":95.72,"temp_max":95.72,"pressure":1013,"sea_level":1013,"grnd_level":997,"humidity":29,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":2},"wind":{"speed":0.25,"deg":324,"gust":3.56},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-07 06:00:00"},{"dt":1662541200,"main":{"temp":91.53,"feels_like":91.89,"temp_min":91.53,"temp_max":91.53,"pressure":1014,"sea_level":1014,"grnd_level":998,"humidity":37,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":2.33,"deg":90,"gust":4.29},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-07 09:00:00"},{"dt":1662552000,"main":{"temp":87.82,"feels_like":89.73,"temp_min":87.82,"temp_max":87.82,"pressure":1014,"sea_level":1014,"grnd_level":998,"humidity":47,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":1.9,"deg":95,"gust":3.31},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-07 12:00:00"},{"dt":1662562800,"main":{"temp":87.26,"feels_like":94.03,"temp_min":87.26,"temp_max":87.26,"pressure":1017,"sea_level":1017,"grnd_level":1000,"humidity":61,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"clouds":{"all":0},"wind":{"speed":4.27,"deg":94,"gust":5.46},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-07 15:00:00"},{"dt":1662573600,"main":{"temp":94.55,"feels_like":100.96,"temp_min":94.55,"temp_max":94.55,"pressure":1016,"sea_level":1016,"grnd_level":1000,"humidity":45,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"clouds":{"all":0},"wind":{"speed":5.3,"deg":103,"gust":6.13},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-07 18:00:00"},{"dt":1662584400,"main":{"temp":101.66,"feels_like":102.16,"temp_min":101.66,"temp_max":101.66,"pressure":1014,"sea_level":1014,"grnd_level":998,"humidity":25,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"clouds":{"all":0},"wind":{"speed":5.75,"deg":98,"gust":8.25},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-07 21:00:00"},{"dt":1662595200,"main":{"temp":102.78,"feels_like":101.17,"temp_min":102.78,"temp_max":102.78,"pressure":1012,"sea_level":1012,"grnd_level":996,"humidity":20,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"clouds":{"all":0},"wind":{"speed":6.42,"deg":117,"gust":7.74},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-08 00:00:00"},{"dt":1662606000,"main":{"temp":96.26,"feels_like":96.26,"temp_min":96.26,"temp_max":96.26,"pressure":1013,"sea_level":1013,"grnd_level":997,"humidity":30,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":5.26,"deg":117,"gust":6.46},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-08 03:00:00"},{"dt":1662616800,"main":{"temp":93.09,"feels_like":92.77,"temp_min":93.09,"temp_max":93.09,"pressure":1013,"sea_level":1013,"grnd_level":997,"humidity":33,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":2.75,"deg":280,"gust":3.29},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-08 06:00:00"},{"dt":1662627600,"main":{"temp":91.8,"feels_like":90.66,"temp_min":91.8,"temp_max":91.8,"pressure":1011,"sea_level":1011,"grnd_level":995,"humidity":32,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":4.63,"deg":296,"gust":5.26},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-08 09:00:00"},{"dt":1662638400,"main":{"temp":82.94,"feels_like":86.76,"temp_min":82.94,"temp_max":82.94,"pressure":1012,"sea_level":1012,"grnd_level":996,"humidity":64,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":2.04,"deg":31,"gust":3.67},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-08 12:00:00"},{"dt":1662649200,"main":{"temp":86.65,"feels_like":91.22,"temp_min":86.65,"temp_max":86.65,"pressure":1012,"sea_level":1012,"grnd_level":996,"humidity":57,"temp_kf":0},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"clouds":{"all":0},"wind":{"speed":4.79,"deg":111,"gust":5.73},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-08 15:00:00"},{"dt":1662660000,"main":{"temp":91.9,"feels_like":97.29,"temp_min":91.9,"temp_max":91.9,"pressure":1010,"sea_level":1010,"grnd_level":994,"humidity":48,"temp_kf":0},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"clouds":{"all":38},"wind":{"speed":5.3,"deg":97,"gust":4.43},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-08 18:00:00"},{"dt":1662670800,"main":{"temp":99.64,"feels_like":102.29,"temp_min":99.64,"temp_max":99.64,"pressure":1007,"sea_level":1007,"grnd_level":991,"humidity":31,"temp_kf":0},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"clouds":{"all":82},"wind":{"speed":6.49,"deg":103,"gust":7.18},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-08 21:00:00"},{"dt":1662681600,"main":{"temp":98.38,"feels_like":100.67,"temp_min":98.38,"temp_max":98.38,"pressure":1004,"sea_level":1004,"grnd_level":989,"humidity":32,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"clouds":{"all":91},"wind":{"speed":4.27,"deg":115,"gust":5.57},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-09 00:00:00"},{"dt":1662692400,"main":{"temp":94.01,"feels_like":96.22,"temp_min":94.01,"temp_max":94.01,"pressure":1005,"sea_level":1005,"grnd_level":989,"humidity":38,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":98},"wind":{"speed":0.43,"deg":302,"gust":2.59},"visibility":10000,"pop":0.08,"sys":{"pod":"n"},"dt_txt":"2022-09-09 03:00:00"},{"dt":1662703200,"main":{"temp":91.24,"feels_like":92.17,"temp_min":91.24,"temp_max":91.24,"pressure":1004,"sea_level":1004,"grnd_level":988,"humidity":39,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":98},"wind":{"speed":3.06,"deg":286,"gust":3.47},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-09 06:00:00"},{"dt":1662714000,"main":{"temp":81.39,"feels_like":83.91,"temp_min":81.39,"temp_max":81.39,"pressure":1006,"sea_level":1006,"grnd_level":990,"humidity":62,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":100},"wind":{"speed":4.63,"deg":62,"gust":6.29},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-09 09:00:00"},{"dt":1662724800,"main":{"temp":79,"feels_like":79,"temp_min":79,"temp_max":79,"pressure":1005,"sea_level":1005,"grnd_level":989,"humidity":71,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":100},"wind":{"speed":2.51,"deg":60,"gust":4.79},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2022-09-09 12:00:00"},{"dt":1662735600,"main":{"temp":80.55,"feels_like":83.55,"temp_min":80.55,"temp_max":80.55,"pressure":1006,"sea_level":1006,"grnd_level":990,"humidity":68,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"clouds":{"all":100},"wind":{"speed":3.8,"deg":64,"gust":5.48},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-09 15:00:00"},{"dt":1662746400,"main":{"temp":87.75,"feels_like":90.99,"temp_min":87.75,"temp_max":87.75,"pressure":1006,"sea_level":1006,"grnd_level":990,"humidity":51,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"clouds":{"all":100},"wind":{"speed":8.95,"deg":91,"gust":17.07},"visibility":10000,"pop":0,"sys":{"pod":"d"},"dt_txt":"2022-09-09 18:00:00"},{"dt":1662757200,"main":{"temp":83.46,"feels_like":87.93,"temp_min":83.46,"temp_max":83.46,"pressure":1005,"sea_level":1005,"grnd_level":989,"humidity":65,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"clouds":{"all":100},"wind":{"speed":9.75,"deg":102,"gust":15.77},"visibility":10000,"pop":0.16,"sys":{"pod":"d"},"dt_txt":"2022-09-09 21:00:00"},{"dt":1662768000,"main":{"temp":80.98,"feels_like":84.6,"temp_min":80.98,"temp_max":80.98,"pressure":1004,"sea_level":1004,"grnd_level":988,"humidity":70,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"clouds":{"all":100},"wind":{"speed":9.42,"deg":79,"gust":24.18},"visibility":10000,"pop":0.37,"rain":{"3h":1.03},"sys":{"pod":"d"},"dt_txt":"2022-09-10 00:00:00"},{"dt":1662778800,"main":{"temp":76.71,"feels_like":78.13,"temp_min":76.71,"temp_max":76.71,"pressure":1004,"sea_level":1004,"grnd_level":988,"humidity":86,"temp_kf":0},"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10n"}],"clouds":{"all":100},"wind":{"speed":10.13,"deg":16,"gust":15.84},"visibility":3866,"pop":0.88,"rain":{"3h":8.03},"sys":{"pod":"n"},"dt_txt":"2022-09-10 03:00:00"},{"dt":1662789600,"main":{"temp":77.85,"feels_like":79.41,"temp_min":77.85,"temp_max":77.85,"pressure":1005,"sea_level":1005,"grnd_level":989,"humidity":87,"temp_kf":0},"weather":[{"id":502,"main":"Rain","description":"heavy intensity rain","icon":"10n"}],"clouds":{"all":100},"wind":{"speed":8.9,"deg":67,"gust":15.05},"visibility":2520,"pop":1,"rain":{"3h":13.28},"sys":{"pod":"n"},"dt_txt":"2022-09-10 06:00:00"},{"dt":1662800400,"main":{"temp":76.24,"feels_like":78.08,"temp_min":76.24,"temp_max":76.24,"pressure":1005,"sea_level":1005,"grnd_level":988,"humidity":96,"temp_kf":0},"weather":[{"id":502,"main":"Rain","description":"heavy intensity rain","icon":"10n"}],"clouds":{"all":100},"wind":{"speed":8.21,"deg":85,"gust":12.82},"visibility":284,"pop":0.99,"rain":{"3h":14.58},"sys":{"pod":"n"},"dt_txt":"2022-09-10 09:00:00"},{"dt":1662811200,"main":{"temp":73.42,"feels_like":74.88,"temp_min":73.42,"temp_max":73.42,"pressure":1007,"sea_level":1007,"grnd_level":991,"humidity":94,"temp_kf":0},"weather":[{"id":502,"main":"Rain","description":"heavy intensity rain","icon":"10n"}],"clouds":{"all":100},"wind":{"speed":6.73,"deg":89,"gust":12.12},"visibility":519,"pop":1,"rain":{"3h":18.39},"sys":{"pod":"n"},"dt_txt":"2022-09-10 12:00:00"},{"dt":1662822000,"main":{"temp":74.17,"feels_like":75.52,"temp_min":74.17,"temp_max":74.17,"pressure":1010,"sea_level":1010,"grnd_level":993,"humidity":90,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"clouds":{"all":100},"wind":{"speed":4.45,"deg":82,"gust":7.65},"visibility":853,"pop":1,"rain":{"3h":2.28},"sys":{"pod":"d"},"dt_txt":"2022-09-10 15:00:00"},{"dt":1662832800,"main":{"temp":76.66,"feels_like":77.92,"temp_min":76.66,"temp_max":76.66,"pressure":1011,"sea_level":1011,"grnd_level":994,"humidity":83,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"clouds":{"all":99},"wind":{"speed":5.95,"deg":98,"gust":10.58},"visibility":4886,"pop":1,"rain":{"3h":1.15},"sys":{"pod":"d"},"dt_txt":"2022-09-10 18:00:00"},{"dt":1662843600,"main":{"temp":79.83,"feels_like":79.83,"temp_min":79.83,"temp_max":79.83,"pressure":1010,"sea_level":1010,"grnd_level":994,"humidity":73,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"clouds":{"all":99},"wind":{"speed":4.59,"deg":98,"gust":9.37},"visibility":10000,"pop":0.75,"rain":{"3h":1.11},"sys":{"pod":"d"},"dt_txt":"2022-09-10 21:00:00"},{"dt":1662854400,"main":{"temp":80.85,"feels_like":84.36,"temp_min":80.85,"temp_max":80.85,"pressure":1009,"sea_level":1009,"grnd_level":993,"humidity":70,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"clouds":{"all":99},"wind":{"speed":5.14,"deg":108,"gust":7.31},"visibility":10000,"pop":0.84,"rain":{"3h":1.43},"sys":{"pod":"d"},"dt_txt":"2022-09-11 00:00:00"},{"dt":1662865200,"main":{"temp":79.84,"feels_like":79.84,"temp_min":79.84,"temp_max":79.84,"pressure":1011,"sea_level":1011,"grnd_level":994,"humidity":72,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"clouds":{"all":100},"wind":{"speed":3.36,"deg":117,"gust":5.55},"visibility":10000,"pop":0.83,"rain":{"3h":0.84},"sys":{"pod":"n"},"dt_txt":"2022-09-11 03:00:00"},{"dt":1662876000,"main":{"temp":79.72,"feels_like":79.72,"temp_min":79.72,"temp_max":79.72,"pressure":1012,"sea_level":1012,"grnd_level":996,"humidity":73,"temp_kf":0},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"clouds":{"all":98},"wind":{"speed":1.03,"deg":40,"gust":3.29},"visibility":10000,"pop":0.75,"rain":{"3h":0.16},"sys":{"pod":"n"},"dt_txt":"2022-09-11 06:00:00"},{"dt":1662886800,"main":{"temp":79.48,"feels_like":79.48,"temp_min":79.48,"temp_max":79.48,"pressure":1012,"sea_level":1012,"grnd_level":995,"humidity":72,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":95},"wind":{"speed":2.1,"deg":84,"gust":4.72},"visibility":10000,"pop":0.05,"sys":{"pod":"n"},"dt_txt":"2022-09-11 09:00:00"},{"dt":1662897600,"main":{"temp":79.5,"feels_like":79.5,"temp_min":79.5,"temp_max":79.5,"pressure":1012,"sea_level":1012,"grnd_level":996,"humidity":73,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":96},"wind":{"speed":3.47,"deg":104,"gust":4.63},"visibility":10000,"pop":0.08,"sys":{"pod":"n"},"dt_txt":"2022-09-11 12:00:00"},{"dt":1662908400,"main":{"temp":79.7,"feels_like":79.7,"temp_min":79.7,"temp_max":79.7,"pressure":1014,"sea_level":1014,"grnd_level":998,"humidity":73,"temp_kf":0},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"clouds":{"all":99},"wind":{"speed":3.13,"deg":96,"gust":4.18},"visibility":10000,"pop":0.05,"sys":{"pod":"d"},"dt_txt":"2022-09-11 15:00:00"},{"dt":1662919200,"main":{"temp":84.87,"feels_like":88.41,"temp_min":84.87,"temp_max":84.87,"pressure":1014,"sea_level":1014,"grnd_level":998,"humidity":58,"temp_kf":0},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"clouds":{"all":84},"wind":{"speed":4.52,"deg":94,"gust":5.99},"visibility":10000,"pop":0.03,"sys":{"pod":"d"},"dt_txt":"2022-09-11 18:00:00"}],"city":{"id":5380668,"name":"Palm Springs","coord":{"lat":33.8303,"lon":-116.5453},"country":"US","population":44552,"timezone":-25200,"sunrise":1662470615,"sunset":1662516349}}
I've not dug into your code, but I can pretty much guarantee that your issue will be down to you not querying the correct nested level of the JSON Object. Looking at the JSON data you get back from the API call, within the main Object, there is then a 'City' Object, which has the key 'name' against it. Make sure you're querying the correct level.
The structure you need to get the data you need is essentially the following pseudo code: JsonObjectFromAPIResponse.get("city").get("name")
Just translate this into what you're doing. Debug it step by step. You're over complicating it in your code example before you've got the basics working. Forget about the City Objects and Factories you've been creating, just get it working in a single file, then refactor it after.
thanks for response. i was able to figure out the correct way to walk down the json tree. i was just coding the format incorrect.
this worked
print('justcity name:');
// printout Palm SPrings ok.
print(data['city']['name']);
//print(justList[0]);
final justTemp = data['list'][0]['main']['temp'];
print('justTemp:');
this json tool help me understand the json tree better for my very long and complex json response from host api.
https://jsonpathfinder.com/

dart/Flutter: Problems with Decodeing json with utf8 decode

I try to load a json-file to put it in a filterable/searchable Listview (search for a diagnosis with a symptom). I'm new to in programming so probably there is a better / simpler way to do this but i would like to do it this way, so it doesnt get more complicated.
I get this error if i try to use utf8.decode:
"The argument type 'String' can't be assigned to the parameter type 'List'."
This is what i tried:
class Services {
static Future<List<User>> getUsers() async {
final response = await rootBundle.loadString('assets/diff.json');
List<User> list = parseUsers(response);
return list;
}
static List<User> parseUsers(String responseBody) {
final parsed = json.decode(utf8.decode(responseBody)).cast<Map<String, dynamic>>();
return parsed.map<User>((json) => User.fromJson(json)).toList();
}
}
the User Class:
class User {
String symptom;
String diagnosis;
User(this.symptom, this.diagnosis);
User.fromJson(Map<String, dynamic> json){
symptom = json['symptom'];
diagnosis = json['diagnosis'];
}
}
extract of the json file:
[
{"symptom":"Kopfschmerz","diagnosis":"Migräne, Spannungskopfschmerz"}
,
{"symptom":"Bauchschmerz","diagnosis":"Apendizitis, Infektion"}
]
Is there a simple way to make this work? Thanks!
With dynamic json.decode(String) the returned object can have a real type of:
List<dynamic>
Map<String, dynamic>
But also when the type is List<dynamic>, decode has parsed also the items in the List, so in your case (since your json has structure [{"" : ""}]) you just need to cast the (reified) List's type parameter with the cast() method.
static List<User> parseUsers(String responseBody) {
//final parsed = json.decode(utf8.decode(responseBody)).cast<Map<String, dynamic>>();
final parsed = (json.decode(responseBody) as List<dynamic>).cast<Map<String, dynamic>>();
return parsed.map<User>((json) => User.fromJson(json)).toList();
}

Iterate items in ResponseBody and put them in a HashMap Spring Boot

In a REST controller in Spring boot, I am trying to iterate the values in a RequestBody response and put some of them in a HashMap in a POST endpoint.
The JSON I am sending is of this structure:
{"name":"yogurt","vitaminA":6,"vitaminb12":5}
The endpoint looks like this so far:
#RequestMapping("/create")
public NutrientList createNUtrientList(#RequestBody NutrientList nutrientList) {
Map<String, Double> nutrientMap = new HashMap<String,Double>();
//get nutrient values, need help with this part
for()
//add values to map
NutrientList nl = new NutrientList(nutrientList.getName(), nutrientMap);
//will save to repository
return nl;
}
The NutrientList class looks like this:
public class NutrientList {
#Id
private ObjectId id;
#JsonProperty("name")
private String name;
#JsonProperty("nutrientMap")
Map <String,Double> nutrientMap = new HashMap<String,Double>();
public NutrientList() {}
public NutrientList(String name, Map<String, Double> nutrientMap) {
this.id = new ObjectId();
this.name = name;
this.nutrientMap = nutrientMap;
}
//setters and getters
}
The data is stored by separate nutrient in the database, it is not a map. I see the NutrientList class does not share the same structure, but is there any way I can get around this to be able to use a map without changing how it is stored in the database?
I need to use a map because there are many nutrients and I don't want to have separate variables for them. Thank you so much. Let me know if something is not clear.
EDIT:
I could alternately turn the csv where I got the data in the database from into JSON format with the map, but I have not found a tool online that gives me this flexibility.
If you have a list of valid keys, you could use the following:
private static final List<String> validKeys = Arrays.asList("vitaminA", "vitaminB" /* ... */);
#RequestMapping("/create")
public NutrientList createNutrientList(#RequestBody Map<String, Object> requestBody) {
Map<String, Double> nutrientMap = new HashMap<>();
for (String nutrient : requestBody.keySet()) {
if (validKeys.contains(nutrient) && requestBody.get(nutrient) instanceof Number) {
Number number = (Number) requestBody.get(nutrient);
nutrientMap.put(nutrient, number.doubleValue());
}
}
String name = (String) requestBody.get("name"); // maybe check if name exists and is really a string
return new NutrientList(name, nutrientMap);
}
If you want to use Java 8 Stream API you can try:
private static final List<String> validKeys = Arrays.asList("vitaminA", "vitaminB" /* ... */);
#RequestMapping("/create")
public NutrientList createNutrientList(#RequestBody Map<String, Object> requestBody) {
Map<String, Double> nutrientMap = requestBody.entrySet().stream()
.filter(e -> validKeys.contains(e.getKey()))
.filter(e -> e.getValue() instanceof Number)
.collect(Collectors.toMap(Map.Entry::getKey, e -> ((Number) e.getValue()).doubleValue()));
String name = Optional.ofNullable(requestBody.get("name"))
.filter(n -> n instanceof String)
.map(n -> (String) n)
.orElseThrow(IllegalArgumentException::new);
return new NutrientList(name, nutrientMap);
}
Hope that helps.

parse JSON with gson and GsonBuilder()

String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
This is my json string. How can i parse it to GsonBuilder() that i will get object back? I try few thinks but none works.
I also read https://sites.google.com/site/gson/gson-user-guide
public class YourObject {
private String appname;
private String Version;
private String UUID;
private String WWXY;
private String ABCD;
private String YUDE;
//getters/setters
}
parse to Object
YourObject parsed = new Gson().fromJson(jsons, YourObject.class);
or
YourObject parsed = new GsonBuilder().create().fromJson(jsons, YourObject.class);
minor test
String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
YourObject parsed = new Gson().fromJson(jsons, YourObject.class);
works well
EDIT
in this case use JsonParser
JsonObject object = new JsonParser().parse(jsons).getAsJsonObject();
object.get("appname"); // application
object.get("Version"); // 0.1.0
JSON uses double quotes ("), not single ones, for strings so the JSON you have there is invalid. That's likely the cause of any issues you're having converting it to an object.

How to deserialize JSON string between JSON.org library using GSON library

I have a problem when using GSON library which is json library from Google. Hope someone can give me some hint.
The problem is when I use the gson.fromJson() function trying to convert a json string to a specified defined class.
The example code:
String jsonStr = "{name:"ABC", countries:["US"]}"; // Some Json string.
Gson gson = new Gson();
Example example = gson.fromJSON(jsonStr, Example.class);
class Example {
// does no have no-arg constructor
private String name;
private Integer age;
private JSONArray keywords; // import org.json.JSONArray;
private JSONArray countries;
// other codes
}
The above code is simplied version of my problem.
The problem is in the fromJson() function. The error message is saying "JsonParseException: Expecting object found ["US"]".
I can not figure out what the problem is. I guess maybe gson does not know how to covert a string to JSONArray. Because in here, JSONArray is from another library(org.json).
I try to figure out in the gson documents. It look like I need to write some "Instance Creator" code.
I am wondering whether another can give me some solution. Thank you.
Just make keywords and countries a java List type. I've never seen org.json mixed with gson. Usually gson replaces org.json it's not meant to be used together.
EDIT:
Small example:
class Example {
private String name;
private Integer age;
private List<String> keywords;
private List<String> countries;
public String toString() {
return new Gson().toJson(this);
}
}