Cast json in to Map<String,Map<String,String>> Format - dart

I need to convert the json string to nested Map and access the same.
Following Json String is in form of Map given below
Map<String,Map<String,String>>
{"0":{"1551874690005":"2","1551874722124":"2","1551874810817":"2","1551874681110":"2","1551874739821":"2","1551874763604":"2","1551874692381":"2","1551874816028":"2","1551874708292":"2","1551874804308":"2","1551874694205":"2","1551874696644":"2","1551874729332":"2","1551874749950":"2","1551874767786":"2"},"1":{"1551948649643":"0","1551948733576":"0","1551948601167":"0","1551948592816":"0","1551948699297":"0","1551874822043":"2","1551948681513":"0","1551948531568":"0","1551948577374":"0","1551948719758":"0","1552370125650":"0","1551948549863":"0","1551948564519":"0","1551948631000":"0","1551953956716":"0"},"2":{"1551875011432":"0","1551875020618":"0","1551874991952":"0","1551875091300":"0","1551875073622":"0","1551875032851":"0","1551874827691":"0","1551948658122":"0","1551874846523":"0","null":"0","1552545417127":"0","1551875083856":"0","1551874929076":"0","1552545972738":"0"},"3":{"1552651031695":"0"},"4":{"1551875144268":"0","1551875157028":"0","1551875115211":"0","1551875124660":"0"}}
Getting following error while trying using my code:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>' in type cast
Map offlineExeStatus = jsonDecode(prefs.getString("offlineExeStatus"));
Map<String,Map<String,String>> exeStatusFinalJson = new Map();
exeStatusFinalJson = offlineExeStatus.cast<String,Map<String,String>();
Need to cast the given json in "exeStatusFinalJson" Map and access like:
exeStatusFinalJson["0"] should give the output like:
{"1551874690005":"2","1551874722124":"2","1551874810817":"2","1551874681110":"2","1551874739821":"2","1551874763604":"2","1551874692381":"2","1551874816028":"2","1551874708292":"2","1551874804308":"2","1551874694205":"2","1551874696644":"2","1551874729332":"2","1551874749950":"2","1551874767786":"2"}

Try to declare your map as Map<String, dynamic> rather than Map<String, Map<String, String>>.

Finally figured out the way to do it!
Map offlineExeStatus = jsonDecode(prefs.getString("onlineExeStatus"));
Map<String, dynamic> exeStatusJson = new Map();
Map<String, Map<String, String>> exeStatusFinalJson = new Map();
List<String> mapKeyExe = new List();
mapKeyExe = offlineExeStatus.keys.cast<String>().toList();
exeStatusJson = offlineExeStatus.cast<String, dynamic>();
for (int i = 0; i < mapKeyExe.length; i++) {
Map<String, String> exeStatusInsideJson = new Map();
exeStatusInsideJson = offlineExeStatus[mapKeyExe[i].toString()]
.cast<String, String>();
exeStatusFinalJson[i.toString()] = exeStatusInsideJson;
print(exeStatusFinalJson);
}

Related

How to retrieve the first key from Gee.SortedMap in Vala?

How do I retrieve the first key from Gee.SortedMap in Vala?
For example if I have
Gee.SortedMap<int, string> foo = new Gee.TreeMap<int, string> ();
I want to get the first key, i.e. the lowest int in foo.
In Java we have java.util.SortedMap.firstKey(). I cannot find an equivalent in Vala.
The SortedMap has an ascending_keys property that returns a SortedSet. Then you can get the first() item from the SortedSet:
void main () {
Gee.SortedMap<int, string> foo = new Gee.TreeMap<int, string> ();
foo.set(2, "two");
foo.set(1, "one");
foo.set(0, "zero");
print(#"First sorted key: $(foo.ascending_keys.first())\n");
}

How to resolve type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>

I am trying to fetch user data but getting below error while doing so:
Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>
I looked at various solutions for similar issue and changed my code accordingly (ex: used <String, dynamic> instead of <dynamic, dynamic>, but still am seeing this error.
Model snippet:
// Returns a Pro created from JSON
factory Pro.fromJson(Map<String, dynamic> json) {
Pro pro = Pro();
pro.uid = json['uid'];
pro.email = json['email'];
And fetching this data as below and calling this method in initState():
Future<Pro> _getPro() async {
await userDatabaseReference.once().then((DataSnapshot snapshot) {
Map<String, dynamic> values = snapshot.value;
values["uid"] = snapshot.key;
print(snapshot.key);
Pro fetchedUser = Pro.fromJson(values);
setState(() {
this.pro = fetchedUser;
});
});
}
If I use Map<String, dynamic> values, then I get error at same line and if I use Map<dynamic, dynamic> values, then I get error at:
Pro fetchedUser = Pro.fromJson(values)
Since, Pro.fromJson(values) has parameter type Map<String, dynamic> which is the same parameter type I used to declare values but still not sure why its throwing the error.
Please try as below where we convert values first into Map.from() and then use that with fromJson method of Pro model:
Future<Pro> _getPro() async {
await userDatabaseReference.once().then((DataSnapshot snapshot) {
Map<String, dynamic> values = snapshot.value;
values["uid"] = snapshot.key;
print(snapshot.key);
final mapJsonCategory = Map<String, dynamic>.from(values);
Pro fetchedUser = Pro.fromJson(mapJsonCategory);
setState(() {
this.pro = fetchedUser;
});
});
}

Flutter _TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')

I am new to flutter and getting type error. I am trying to use json automated serializations.
AFTER DOING SOME TWEAKS HERE IS HOW IT LOOKS LIKE
Here is how I am trying to get the data from api
Future getMyProduct() async {
final res = await http.get('url');
final data = json.decode(res.body);
BaseResponse req = new BaseResponse.fromJson(data);
return req;
}
My BaseResponse class looks like this
import 'package:dynamicapp/model/model.dart';
import 'package:json_annotation/json_annotation.dart';
part 'response.g.dart';
#JsonSerializable()
class BaseResponse extends Object {
final int id;
final int sellingPrice;
final int totalStock;
final String productName;
final String productDesc;
final List<Image> images;
BaseResponse(this.id, this.sellingPrice, this.totalStock, this.productName,
this.productDesc, this.images);
factory BaseResponse.fromJson(Map<String, dynamic> json) => _$BaseResponseFromJson(json);
Map<String, dynamic> toJson() => _$BaseResponseToJson(this);
}
#JsonSerializable()
class Image extends Object {
final int id;
final String image;
// final int product_id;
Image(this.id, this.image);
factory Image.fromJson(Map<String, dynamic> json) => _$ImageFromJson(json);
Map<String, dynamic> toJson() => _$ImageToJson(this);
}
Could anyone please help me with this. I am stuck here. Have been trying different methods but none working. Thank you.
It looks like data is a List<dynamic>, then data.map(someFunc).toList() will take each element of data pass it to someFunc and form it back into a list of the return type of someFunc (which you will presumably want to be BaseResponse). Which tells you that someFunc needs to be a function that takes dynamic and returns BaseResponse.
You'd want to write something like this:
final data = json.decode(res.body);
List<BaseResponse> responses =
data.map((j) => BaseResponse.fromJson(j)).toList();

How to set the value in hashmap key:value pair conditionally?

I'am using grails.
I want to set the values in map conditionally.
For Eg:
HashMap<String, String> mymap= new HashMap<String, String>();
if (author != null){
mymap['TITLE'] = book.title
}else{
mymap['TITLE'] = 'NA'
}
So, what I want to acheive is, I want to set the value of my title as "book.title" if the particular value is not null otherwise it should be a normal string "NA".
Output I'am Getting
mymap:[TITLE: NA]
Output I want
mymap:[TITLE: [TITLE1, TITLE2, NA, TITLE4, TITLE5]]
Something like this
Thanks in advance.
You are using groovy all of this can be done more elegantly:
You must be getting iteration of book from somewhere ?
Change this from:
HashMap<String, String> mymap= new HashMap<String, String>();
if (author != null){
mymap['TITLE'] = book.title
}else{
mymap['TITLE'] = 'NA'
}
to:
List titles=[]
books?.title?.each { title->
titles<< (title?:'NA')
}
def mymap=['TITLE':titles]
Use this instead :
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> myList = new ArrayList<String>();
if (author != null){
myList.add(book.title)
}else{
myList.add('NA')
}
map.put("TITLE",myList) ;
Shorter variant:
HashMap<String, List<String>> map = [:].withDefault{ [] }
map[ 'TITLE' ] << ( author ? book.title : 'NA' )

enumerate resource-bundles defined in faces-config.xml

I am using a mojarra-specific code for this:
public static Map<String, ResourceBundle> getBundleMap()
{
Locale locale = Faces.getLocale();
ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance();
Map<String, ApplicationResourceBundle> resourceBundles = associate.getResourceBundles();
Map<String, ResourceBundle> map = new HashMap<>(resourceBundles.size());
for(Entry<String, ApplicationResourceBundle> entry : resourceBundles.entrySet())
{
String name = entry.getKey();
ResourceBundle bundle = entry.getValue().getResourceBundle(locale);
map.put(name, bundle);
}
return map;
}
I'd like to have an implementation-agnostic way to get this map.
Should I parse every faces-config.xml defined in application and libs? Isn't this reinventing the wheel?
A Map<String, String>, where key = /faces-config/application/resource-bundle/var and value = /faces-config/application/resource-bundle/base-name would be sufficient.
Thanks.
I'd like to have an implementation-agnostic way to get this map.
Understandable.
Should I parse every faces-config.xml defined in application and libs?
Yes. This functionality isn't available in JSF API.
Isn't this reinventing the wheel?
Yes, definitely. You could however try to get it into OmniFaces, which has already a similar utility class for /WEB-INF/web.xml and all /META-INF/web-fragment.xml, the WebXml.
A Map<String, String>, where key = /faces-config/application/resource-bundle/var and value = /faces-config/application/resource-bundle/base-name would be sufficient.
Here's a kickoff example using JAXP (cough):
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(false);
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.appendChild(document.createElement("all-faces-configs"));
List<URL> facesConfigURLs = new ArrayList<>();
facesConfigURLs.add(FacesContext.getCurrentInstance().getExternalContext().getResource("/WEB-INF/faces-config.xml"));
facesConfigURLs.addAll(Collections.list(Thread.currentThread().getContextClassLoader().getResources("META-INF/faces-config.xml")));
for (URL facesConfigURL : facesConfigURLs) {
URLConnection connection = facesConfigURL.openConnection();
connection.setUseCaches(false);
try (InputStream input = connection.getInputStream()) {
NodeList children = builder.parse(input).getDocumentElement().getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
document.getDocumentElement().appendChild(document.importNode(children.item(i), true));
}
}
}
Map<String, String> resourceBundles = new HashMap<>();
Element allFacesConfigs = document.getDocumentElement();
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList resourceBundleNodes = (NodeList) xpath.compile("application/resource-bundle").evaluate(allFacesConfigs, XPathConstants.NODESET);
for (int i = 0; i < resourceBundleNodes.getLength(); i++) {
Node resourceBundleNode = resourceBundleNodes.item(i);
String var = xpath.compile("var").evaluate(resourceBundleNode).trim();
String baseName = xpath.compile("base-name").evaluate(resourceBundleNode).trim();
resourceBundles.put(var, baseName);
}

Resources