Dynamic Lists to String Lists - dart

I am getting data from my firestore, but I am only interested in the array part for this. I've prepared a dartpad for it:
https://dartpad.dev/9b99f0e2e8c83913f9cd2bd71bd70d81
How do I convert List data = ['Room 1', 'Room 2']; to List<String> stringData = ['Room 1', 'Room 2'];
There are similar questions, but I am probably too stupid to understand how the fix works, I tried to implement them but I think their input data looks a bit different. (like these: How to cast <dynamic> to List<String>? or How to Create DropdownButton with a list of JSON data within a list in flutter)

Use cast():
List data = ['Room 1', 'Room 2'];
List<String> stringData;
void main() {
stringData = data.cast<String>(); // <- look here
print(stringData);
print(data);
}

Related

How to convert a list inside of a list from json in dart

Imagine you have the following json
{
"list": [
["xa", "yc", "ze"],
["xb", "yd", "zf"]
]
}
how do we convert this to a List<List<String>> with json.decode() in dart?
I'm going to make the assumption that this is a string before you pass it to jsonDecode, which will return a Map<String, dynamic>.
// The original string
String jsonString = "{\"list\": [[\"xa\", \"yc\", \"ze\"], [\"xb\", \"yd\", \"zf\"]]}";
// The parsed map
Map<String, dynamic> json = jsonDecode(jsonString);
Now, it seems like you don't care about the containing Map.
Technically, those things that look like Lists are actually Maps at this point, so those type assertions would fail.
List<List<String>> output = json["list"].map((value) => value.toList()).toList();
That's the most straightforward method I can think of right now.

How do I convert an array in a map to array of strings

I'm trying to convert this map {[string1,string2]}
in to an array like this
[string1, string2]
in dart
A declaration of that kind in Dart is a Set(which is like a list but cannot have duplicates) of Lists, given that to get the first value you should just use
obj.first
(Sets are declared like maps but without any key)
This is a Set.
So you can do this for convert it to list:
Set<List<String>> map = {['string1','string2']};
List list = [];
map.forEach((k) {
k.forEach((item) => list.add(item));
});
as already mentioned in other answers this is a Set
you can easy convert it to List like this
var mySet = {['string1', 'string2']};
var list = mySet.expand((e) => e).toList();
print(list); // [string1, string2]
The 'map' you gave has one key (list of strings), which seems to be missing a value.
If your map looked something like this:
Map<List<String>, int> map = {[string1,string2]: 0};
Then you could get an Iterable of your keys (or values if you wish) with:
dynamic temp = map.keys //for the keys or
//or temp = map.values //for the values
You can further convert that Iterable into a List by calling the function toList() on it:
List<String> myList = temp.toList();
I hope this answered your question.
And if you are not sure what the type of your object is, use:
print(yourObject.runTimeType);

How does the Dart URI class QueryParameters handle Map values?

According to the documentation, it needs to follows the Form Post rules at: https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4. When looking at that information it did not give me much to work with in terms of complex objects or maps.
Right now, If I have a list for example: Each item in the list needs to be stringified.
var params = {"list": [1,2,3]};
// needs to be stringed.
params["list"] = params["list"].map((item)=>item.toString()).toList();
Simple. Also all base items need to be a string as well
var params = {"number": 1, "boolean": true};
params = params.forEach((k,v)=> params[k].toString());
But how do we handle maps?
var params = {"map": {"a":1,"b":"foo","c":false,"d":[]}};
// ??
It seems that after testing in my app and in dart pad, you need to make sure everything is strings, so i am trying to come up with a way to effectively cover lists, maps, and maybe more complex objects for encoding.
var params = {};
params["list"] = [1,2,3];
params["number"] = 1;
params["boolean"] = true;
params["map"] = {"a":1,"b":"foo","c":false,"d":[]};
params.forEach((String key, dynamic value){
if(value is List){
params[key] = value.map((v)=>v.toString()).toList();
}else if(value is Map){
// ????
}else{
params[key] = value.toString();
}
//maybe have an additional one for custom classes, but if they are being passed around they should already have their own JSON Parsing implementations.
}
Ideally, the result of this would be passed into:
Uri myUri = new Uri(queryParameters: params);
and right now, while i solved the list issue, it doesn't like receiving maps. Part of me just wanted to stringify the map as a whole, but i wasn't not sure if there was a better way. I know that when someone accidentally stringified the array, it was not giving me: ?id=1&id=2 but instead ?id=%5B1%2C2%5D which was not correct.
I don't think there is any special support for maps. Query parameters itself is a map from string to string or string to list-of-strings.
Everything else need to be brought into this format first before you can pass it as query parameter.
A simple approach would be to JSON encode the map and pass the resulting string as a single query parameter.

Accessing a JSON property with SwitfyJSON returns an empty string

I am trying to print a property from a JSON using SwiftyJSON on XCode (obviously with Swift language)
My first line prints well, but the second one prints nothing, I have checked the output of the first println() in an online parser and the striing is consistent:
var jdata = JSON(self.serverResponse)
println("jdata RAW: "+jdata.stringValue)
println("jdata.responseData: "+jdata["responseData"].stringValue)
This is the result of printing both things, as you can see the 2nd one is just blank:
jdata RAW:
{
"responseData": {
"emotion":"",
"lastinput":"What is your favourite color",
"answer":"My favourite color is orange. What is yours?",
"link": {
"href":"",
"target":""
},
"extraData": {
"action":{"name":"displayClickableList","values":[{"label":"green","key":"1"},{"label":"yellow","key":"2"},{"label":"red","key":"3"}]},"type":"list"
},
"responseSession": {
"id":"1ebfcd96c3c1f206dfb4087bc553",
"transaction":"2"
},
"responseDetails": null,
"responseStatus": 200,
"applicationUrl": "http://moto-dev.cloud.com:88/moto-va-1/;jsessionid=1ebfc206dfb4087bc553"
}
}
jdata.responseData:
I am new to Swift, what is going wrong here?
Your property seems to be a dictionary and can't be converted to string value.
But you can simply print it like this:
println("jdata.responseData: \(jdata["responseData"])")
Ok, I have found a way to obtain the contents of the nested "action" property. It seems that Swifty cannot print jdata["responseData"] because it is not a string (it is a Dictionary with more stuff inside) and it cannot convert it to a string either.
The approach that worked for me was to access through the different layers of JSONS to the final property that I want, and -then- handle it.
For example:
var jdata = JSON(data: data!)
var jaction=jdata["responseData"]["extraData"]["action"]
println("jaction")
println(jaction.stringValue)
Will return this:
jaction
%7B%22name%22%3A%22displayClickableList%22%2C%22values%22%3A%5B%7B%22label%22%3A%22green%22%2C%22key%22%3A%221%22%7D%2C%7B%22label%22%3A%22yellow%22%2C%22key%22%3A%222%22%7D%2C%7B%22label%22%3A%22red%22%2C%22key%22%3A%223%22%7D%5D%7D
And only then, since there is no more JSON Nesting going on, I can take that strange string and URLdecode it.
Printing something like (or anything in between):
println(jaction=jdata["responseData"].stringValue) //returns nothing!
println(jaction=jdata["responseData"]["extraData"].stringValue) //returns nothing!
Will return nothing, because the contents are a Dictionary, not a string.
It is not an intuitive behavior, I had to spend the entire morning struggling to understand the way it works, in Android I do this in another way.

Convert IQueryable generic to JSON

I'm producing a projection via:
var query = from book in books
select new
{
label = book.Title,
value = book.ID
};
In my razor page I need to use:
var booksArray = [{
#(json)
}];
such that the resulting array looks like:
label: 'c++',
value: 'c++'
}, {
label: 'java',
value: 'java'
}, {
label: 'php',
value: 'php'
}, {
label: 'coldfusion',
value: 'coldfusion'
}
I've come very very close from a couple different approaches - I can get a string that looks correct on the server side but when rendered to the page itself, all the ' marks become ' .
But focusing on achieving this via JSON.net...
The most likely approach seems like it should be:
var json = JsonConvert.ToString(query);
but that tosses:
Unsupported type: System.Linq.Enumerable+WhereSelectListIterator`2[Project.Entity.Book,<>f__AnonymousType3`2[System.String,System.Int32]]. Use the JsonSerializer class to get the object's JSON representation.
What's the correct JSON.net syntax?
thx
You need a combination of .ToArray() and Html.Raw()
ToArray() to evaluate the query and make JsonConvert happy
var query = from book in books
select new
{
label = book.Title,
value = book.ID
};
var json = JsonConvert.SerializeObject(query.ToArray());
Note: you need to use JsonConvert.SerializeObject if you want to serialize complex types. JsonConvert.ToString is used to convert simple types like bool, guid, int, uri etc.
And in your view Html.Raw to not html encode the JSON:
var booksArray = #(Html.Raw(json))

Resources