I have a Map named map passed as parameter to a function maptojson function i want to return the json for each k,v of the the map i have the following code .it shows the following error pointing to json "Local variable inputJson defined in an enclosing scope must be final or effectively final"
public static JSONObject maptojson(Map map){
JSONObject Jsonobj = null;
map.forEach(
(k, v) -> {
Jsonobj = new JSONObject();//Local variable Jsonobj defined in an enclosing
scope must be final or effectively final
Jsonobj.put("key", k);
Jsonobj.put(val, v);
});
return Jsonobj;
}
CodePudding user response:
You can use:
new JSONObject(map);
That only works if your map is Map<String, String>
but you can map (as in stream::map
) your map from Map<Object, Object>
to Map<String,String>
CodePudding user response:
Don't return null
. Instead return an empty JSONObject
to indicate 'empty'. Then you can remove the assignment happening in the lambda.
CodePudding user response:
Use for loop, that will be easier. There is a reason why for loop is not deprecated in newer java versions.
public static JSONObject maptojson(Map map){
JSONObject jsonobj = null;
for(String key:map.keySet()){
jsonobj = new JSONObject();
jsonobj.put(key, k);
val = map.get(key);
jsonobj.put(val, v);
}
return Jsonobj;
}