My value from json : "[[2.1,2.2],[1.0,2.5]]".
How to convert this string to List<List> ?
You start off with a List<dynamic> so you can just cast each of its elements to List<double>.
void main() {
final decoded = json.decode('[[2.1,2.2],[1.0,2.5]]') as List<dynamic>;
final listDoubleDouble =
decoded.map<List<double>>((e) => e.cast<double>()).toList();
print(listDoubleDouble.runtimeType);
}
String myJSON = '[[2.1,2.2],[1.0,2.5]]';
var json = jsonDecode(myJSON);
print(json[0][0]);
Related
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();
}
Hi im trying to get values from JSOn but when I map a value that is a INT then flutter show that error and no return data :
flutter: type 'String' is not a subtype of type 'int'
This is my model :
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
class Kits {
final String country;
final String franchise;
final String type;
String brand;
String procedure;
String setdesc;
int traymaterialid;
String traydesc;
int referencia;
String descart;
int cantidad;
int homologado;
int bajopresu;
DateTime insdate;
Kits(this.country,this.franchise,this.type, this.brand, this.procedure,this.traydesc, this.traymaterialid);
factory Kits.fromJson(Map<String, dynamic> json) {
return Kits(json['COUNTRY'], json['FRANCHISE'], json['TYPE'], json['BRAND'], json['PROCEDURE'], json['TRAYDESCRIPTION'], json['TRAYMATERIALID'] /* <-- INT*/ );
}
}
class KitsData {
static const url = 'http://app-smith.com/en/kits_API.php?email=miquel#winfor.es&macid=888&passwd=Wcz95f4UGkax5G';
final JsonDecoder _decoder = new JsonDecoder();
Future<List<Kits>> fetch(){
return http.get(url).then((http.Response response){
final String jsonBody = response.body;
//final statusCode = response.statusCode;
/*if (statusCode < 200 || statusCode >= 300 || jsonBody == null){
return List();
}*/
final kitsContainer = _decoder.convert(jsonBody);
final List kitsItems = kitsContainer['kits'];
return kitsItems.map( (kitsRaw) => new Kits.fromJson(kitsRaw) ).toList();
});
}
}
class FetchDataException implements Exception {
String _message;
FetchDataException(this._message);
String toString() {
return "Exception: $_message";
}
}
I don't understand why it's happen because fromJson is only getting the value that I pass the key then in my list I convert to String the value .
Fragment of JSON:
{"kits": [{"COUNTRY":"FR","FRANCHISE":"KNEE","TYPE":"LEGION","BRAND":"REVISION","PROCEDURE":"LEGION REVISION","SETDESCRIPTION":"LEGION REVISION - INSTRUMENTS","TRAYMATERIALID":"551820141LRC","TRAYDESCRIPTION":"INSTR LEGION REVISION","REFERENCIA":"71431722","DESCRIPCIONARTICULO":"LGN SCW LWDG TRL S3 5D X 10P","CANTIDAD":"1","HOMOLOGADO":"","BAJOPRESUPUESTO":"","INS_DATE":"2018-08-23 18:57:04"}
All numeric values are inside quotes, so they are not transferred as int but as String. The error message is correct. If you want them as String either ensure the values are not quoted, if you don't control that use int.parse() to convert them from String to int
I have a .net application in which I am getting a response data in json format. I have used the below code to get the json response.
string details= new System.Net.WebClient().DownloadString(url);
var temp = JsonConvert.DeserializeObject(details.ToString());
I have got a json format object in temp and json format string in details
I am getting an output as below from temp
{"data":
[
{"category":"Community","name":"New Page","access_token":"accesstoken_data1","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"],"id":"1234"},
{"category":"Community","name":"Page ABC","access_token":"accesstoken_data2","perms":["ADMINISTER","EDIT_PROFILE","CREATE_CONTENT","MODERATE_CONTENT","CREATE_ADS","BASIC_ADMIN"],"id":"56789"}
]
,"paging":{"next":"https:\/\/graph.facebook.com\/1100234567\/accounts?access_token=pageAccesstoken&limit=5000&offset=5000&__after_id=77786543"}
}
I need to get the category,name,access_token as key and corresponding data as values in some dictionary.
How can I achieve it?
Hope this will do the required stuffs
private Dictionary<string, object> deserializeToDictionary(string jo)
{
var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
var values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}
This was taken from the following link
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
string json = #"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>
More examples: Serializing Collections with Json.NET
use the org.json.jar
I know convert a JSON code to JSONObject
JSONObject fieldsJson = new JSONObject("{\"a\":\"b\"}");
String value= fieldsJson.getString("a");
But how to convert a JSON code to map
String str = "{\"age\":\"23\",\"name\":\"ganlu\"}";
JSONObject jobj = JSONObject.fromObject(str);
Map<String,String> tmpMap = (Map) JSONObject.toBean(jobj,Map.class);
Set<String> keys = tmpMap.keySet();
for(String key : keys){
System.out.println(key+":"+tmpMap.get(key));
}
May this will help you.
sorry for the silly question, but i am stuck converting for example the following result from a method into Json
public string Test(string input) {
return "Name:" + input;
}
to look like this
{"Name":"Mike"}
Update:
Darin fixed first problem now i am using this way but it is not working
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using(JsonWriter jsonWriter = new JsonTextWriter(sw)) {
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WritePropertyName("Name");
jsonWriter.WriteValue("Mike");
}
I get
'{"Name":{"m_MaxCapacity":2147483647,"Capacity":16,"m_StringValue":"\\"Name\\": \\"Mike\\"","m_currentThread":0}}';
You could use the JavaScriptSerializer class:
public string Test(string input)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { Name = input });
}
Example usage:
string json = Test("Mike"); // json = {"Name":"Mike"}
UPDATE:
Didn't notice you wanted a solution using the Json.NET library. Here's one:
string json = JsonConvert.SerializeObject(new { Name = input });