I have a List<String> data which is like:
{"0":["passFrom","3/9/2018","3/9/2018","anotherMethod","but"],"1":["googleForAlongTIme","3/9/2018","3/9/2018","stillCannotConvert","theLinkHashMap"]}
I need to store to a linkeHashMap with the above data, so far I had try something like below.
ArrayList<String> listdata = new ArrayList<String>();
Map<Integer, List<String>> listMap = new LinkedHashMap<Integer, List<String>>();
if (jsonArray.getString(0).trim()!= null && !jsonArray.getString(0).isEmpty()) {
for (int i = 0; i < jsonArray.length(); i++){
listdata.add(jsonArray.getString(i)); // here is the data which shown above
//trying to use split at here but find out `**["passFrom","3/9/2018","3/9/2018","anotherMethod","but"],"1"**` is not the correct data
/*List<String> bothList= Arrays.asList(listdata.get(i).toString().split(":"));
for (String string : bothList) {
List<String> tempData=Arrays.asList(bothList.toString());
listMap.put(i, tempData);
System.out.println("TeST: " + string);
}*/
}
}
Need some hints and help here, as my final aim is to get the 0,1 integer and below data to store inside the listMap
"passFrom","3/9/2018","3/9/2018","anotherMethod","but"
"googleForAlongTIme","3/9/2018","3/9/2018","stillCannotConvert","theLinkHashMap"
Try this:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class ParseJson {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
final String jsonStr = "{\"0\":[\"passFrom\",\"3/9/2018\",\"3/9/2018\",\"anotherMethod\",\"but\"],\"1\":[\"googleForAlongTIme\",\"3/9/2018\",\"3/9/2018\",\"stillCannotConvert\",\"theLinkHashMap\"]}";
Map<Integer, List<String>> map = objectMapper.readValue(jsonStr, new TypeReference<LinkedHashMap<Integer, List<String>>>(){});
for (Map.Entry<Integer, List<String>> entry : map.entrySet()) {
System.out.printf("For item \"%d\", values are:\n", entry.getKey());
for (String value : entry.getValue()) {
System.out.printf("\t[%s]\n", value);
}
}
}
}
Outputs:
For item "0", values are:
[passFrom]
[3/9/2018]
[3/9/2018]
[anotherMethod]
[but]
For item "1", values are:
[googleForAlongTIme]
[3/9/2018]
[3/9/2018]
[stillCannotConvert]
[theLinkHashMap]
Related
I tried to follow the same way as in <How do I copy an object in Java?>.
But it does not work with Map object in the following codes. I want to copy the original map data to currMap. The current output is
0
1
2
3
null
null
null
I want it to be
0
1
2
3
0
2
3
What am I missing here?
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
class mapCopy{
private Map<Character, Queue<Integer>> map;
mapCopy(Map<Character, Queue<Integer>> map){
this.map=map;
}
mapCopy(mapCopy mapcopy){
this.map=mapcopy.map;
}
Map<Character, Queue<Integer>> getMap(){
return this.map;
}
}
public class Test {
static Map<Character, Queue<Integer>> BuildMap(){
String toMatch="able";
Map<Character, Queue<Integer>> map = new HashMap<>();
int i=0;
for(var c:toMatch.toCharArray()) {
Queue<Integer> q = map.get(c);
if(q==null)
q=new ArrayDeque<Integer>();
q.add(i);
map.put(c, q);
i++;
}
return map;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Character, Queue<Integer>> map = BuildMap();
List<String> dic = Arrays.asList("able", "ale");
for(var d:dic) {
var copy1 = new mapCopy(map);
var copy2 = new mapCopy(copy1);
var currMap = copy2.getMap();
for(var c:d.toCharArray()) {
System.out.println(currMap.get(c).poll());
}
}
}
}
Update 1:
iota's answer is what I look for. Here are the actually codes implemented by adding a copyMap function and adding it to currMap (var currMap = copyMap(map);)
class mapCopy is not needed.
static Map<Character, Queue<Integer>> copyMap(Map<Character, Queue<Integer>> mapcopy){
Map<Character, Queue<Integer>> map = new HashMap<>(mapcopy.size());
mapcopy.forEach((k,v)->{
map.put(k, new ArrayDeque<>(v));
});
return map;
}
Update 2:
Add complete codes
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public class Test {
static Map<Character, Queue<Integer>> BuildMap(){
String toMatch="able";
Map<Character, Queue<Integer>> map = new HashMap<>();
int i=0;
for(var c:toMatch.toCharArray()) {
Queue<Integer> q = map.get(c);
if(q==null)
q=new ArrayDeque<Integer>();
q.add(i);
map.put(c, q);
i++;
}
return map;
}
static Map<Character, Queue<Integer>> copyMap(Map<Character, Queue<Integer>> mapcopy){
Map<Character, Queue<Integer>> map = new HashMap<>(mapcopy.size());
mapcopy.forEach((k,v)->{
map.put(k, new ArrayDeque<>(v));
});
return map;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Character, Queue<Integer>> map = BuildMap();
List<String> dic = Arrays.asList("able", "ale");
for(var d:dic) {
var currMap = copyMap(map);
for(var c:d.toCharArray()) {
System.out.println(currMap.get(c).poll());
}
}
}
}
You can iterate over the Map directly and copy each value into a new Map.
mapCopy(mapCopy mapcopy){
this.map = new HashMap<>(mapcopy.map.size());
mapcopy.map.forEach((k,v)->{
map.put(k, new ArrayDeque<>(v));
});
}
I have a JSON file with following data:
{ "data" : [
{ "ID":"3b071d17-bfe5-4474-a7b4-58c755c7d954",
"value":"328.0"},
{ "ID":"dc4607f9-5955-4dd8-8c1a-abd3719edb6f",
"value":"764.1"},
{ "ID":"a4aa9f3b-599f-4815-5776-20fa38b064b5",
"value":"983.6"},
{ "ID":"c6fb7cd8-381d-93fa-711b-9482ab394ffa",
"value":"351.5"},
{ "ID":"2366a36b-8df2-72db-40bc-bbbe3258f09c",
"value":"539.3"}
]}
How can get the data range from ID dc4607f9-5955-4dd8-8c1a-abd3719edb6f (2nd) to c6fb7cd8-381d-93fa-711b-9482ab394ffa (4th) or to last data? Is it possible to do so?
Here's my attempt:
List<float> dataSave = new ArrayList();
try {
JSONObject objectFromFile = ...; //JSONReadFile
JSONArray dataArray = objectFromFile.getJSONArray("data");
//here will get data from the start ID to end ID
dataSave.add((float)dataArray.getDouble("value");
} catch (JSONException e) {
e.printStackTrace();
}
If i understood correctly you want get the values of the json array starting with the start id and stopping on the end id. both limits are included.
I am pretty sure that there must be a better way but here is my example if it helps you:
convertJsonArrayToMap: generates a map from the JsonArray
getValueBasedOnRange: saves the value of the json object with id startId until endId
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class App
{
static String data = "{ \"data\" : [\r\n" +
" { \"ID\":\"3b071d17-bfe5-4474-a7b4-58c755c7d954\",\r\n" +
" \"value\":\"328.0\"},\r\n" +
" { \"ID\":\"dc4607f9-5955-4dd8-8c1a-abd3719edb6f\",\r\n" +
" \"value\":\"764.1\"},\r\n" +
" { \"ID\":\"a4aa9f3b-599f-4815-5776-20fa38b064b5\",\r\n" +
" \"value\":\"983.6\"},\r\n" +
" { \"ID\":\"c6fb7cd8-381d-93fa-711b-9482ab394ffa\",\r\n" +
" \"value\":\"351.5\"},\r\n" +
" { \"ID\":\"2366a36b-8df2-72db-40bc-bbbe3258f09c\",\r\n" +
" \"value\":\"539.3\"}\r\n" +
"]}";
public static void main(String... args){
JsonParser jsonParser = new JsonParser();
JsonObject objectFromString = jsonParser.parse(data).getAsJsonObject();
JsonArray dataArray= objectFromString.getAsJsonArray("data");
//here will get data from the start ID to end ID
Set<Entry<String, Float>> dataMap = convertJsonArrayToMap(dataArray);
String startId = "dc4607f9-5955-4dd8-8c1a-abd3719edb6f";
String endId = "c6fb7cd8-381d-93fa-711b-9482ab394ffa";
List<Float> dataSave = getValueBasedOnRange(startId, endId,dataMap);
System.out.println(dataSave.toString());
}
//Generate and return the map from the JsonArray parameter
private static Set<Entry<String, Float>> convertJsonArrayToMap(JsonArray dataArray){
Map<String,Float> dataMap = new LinkedHashMap<>();
for (JsonElement currentElement : dataArray) {
JsonObject currentJsonObject = currentElement.getAsJsonObject();
dataMap.put(currentJsonObject.get("ID").getAsString(), currentJsonObject.get("value").getAsFloat());
}
return dataMap.entrySet();
}
//Generate and return the List<Float> from the map parameter
//Save the float value of the object with ID=startId
//Save the float value of the ANY object after startID
//Save the float value of the object with ID=endId and return
private static List<Float> getValueBasedOnRange(String startId, String endId, Set<Entry<String, Float>> dataMap){
boolean collectFlag = false;
List<Float> dataSave = new ArrayList<>();
for(Entry<String, Float> mapEntry : dataMap) {
if(startId.equals(mapEntry.getKey())) {
collectFlag = true;
}
if(collectFlag) {
dataSave.add(mapEntry.getValue());
}
if(endId.equals(mapEntry.getKey())) {
return dataSave;
}
}
return dataSave;
}
I hope it helps.
I am using zookeeper for configuration management for my java microservices. For that I use apache curator and java zookeeper client.
How can I import a configuration file(properties or json) to zookeeper when the microservice initializes?
You should use curator framework if you wanted to load your config in zookeeper. See the post about how you may use curator framework.
There is a some base code example for yml files (for spring config):
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.BoundedExponentialBackoffRetry;
import org.springframework.core.io.ClassPathResource;
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
#Slf4j
public class LoadConfigsInZoo {
// base path of your config
// /CONFIG_PATH/APP_NAME,CONTEXT_NAME
private static final String BASE_PATH = "/configuration/myApp";
private static final String ZOO_URL = "localhost:2181";
private static final String CONFIG_FILE = "bootstrap.yml";
private final ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] args) throws IOException {
new LoadConfigsInZoo().loadConfig();
}
private void loadConfig() throws IOException {
BoundedExponentialBackoffRetry retryPolicy =
new BoundedExponentialBackoffRetry(100, 300, 10);
Map<String, String> config = flattenInnerProperties("", getContentOfYaml(CONFIG_FILE));
try (CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString(ZOO_URL)
.retryPolicy(retryPolicy)
.build()) {
client.start();
for (Map.Entry<String, String> entry : config.entrySet()) {
String path = createPath(BASE_PATH, entry.getKey());
try {
log.info("Try add node with name '{}'", path);
client.create()
.creatingParentsIfNeeded()
.forPath(path, entry.getValue().getBytes());
log.info("Node with name '{}' was created", path);
} catch (Exception e) {
log.warn("Unable to create node by path: {}, exception: {}", path, e.getMessage());
}
}
}
}
// need your own implementation for properties/json files
#SuppressWarnings("unchecked")
private Map<String, Object> getContentOfYaml(String path) throws IOException {
Yaml yaml = new Yaml();
try (InputStream in = new ClassPathResource(path).getInputStream()) {
return yaml.loadAs(in, Map.class);
}
}
#SuppressWarnings("unchecked")
private Map<String, String> getContentOfProperties(String path) throws IOException {
try (InputStream in = new ClassPathResource(path).getInputStream()) {
Properties properties = new Properties();
properties.load(in);
return (Map) (properties);
}
}
#SuppressWarnings("unchecked")
private Map<String, String> getContentOfJson(String path) throws IOException {
try (InputStream in = new ClassPathResource(path).getInputStream()) {
return new ObjectMapper().readValue(in, HashMap.class);
}
}
#SuppressWarnings("unchecked")
private Map<String, String> flattenInnerProperties(String prefix, Map<String, Object> rootMap) {
Map<String, String> result = new HashMap<>();
for (Map.Entry<String, Object> entry : rootMap.entrySet()) {
String newPrefix = prefix.isEmpty() ? entry.getKey() : prefix + "." + entry.getKey();
Object value = entry.getValue();
if (value instanceof Map) {
result.putAll(flattenInnerProperties(newPrefix, (Map<String, Object>) value));
} else if (value instanceof List) {
result.putAll(flattenInnerListInProperties(newPrefix, (List) value));
} else {
result.put(newPrefix, String.valueOf(value));
}
}
return result;
}
#SuppressWarnings("unchecked")
private Map<String, String> flattenInnerListInProperties(String prefix, List value) {
int i = 0;
Map<String, String> result = new HashMap<>();
for (Object v : value) {
String listKey = prefix + "[" + i + "]";
if (v instanceof Map) {
result.putAll(flattenInnerProperties(listKey, (Map) v));
} else if (v instanceof List) {
result.putAll(flattenInnerListInProperties(listKey, (List) v));
} else {
result.put(listKey, String.valueOf(v));
}
i++;
}
return result;
}
private String createPath(String basePath, String configName) {
return basePath + "/" + configName.replaceAll("\\.", "/");
}
}
I had a similar problem, where we were using zookeeper as the config server and the configuration was stored in yml format in file.
Instead of writing code for creating the znode hierarchy dynamically as per yml file, I found a groovy based tool which basically does the same.
You need to have groovy installed and run as below
zookeeperdump.groovy -s localhost:2181 -c /config/application < dump.yml
I am trying to print key value pairs from a json file. The following is the code I'm using.
I get this error:
Can not deserialize instance of java.util.LinkedHashMap out of
START_ARRAY token
I get this error because the json format is array [{}] instead of object {}. I cannot alter the incoming json file.
How do I go about this?
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test4 {
public static void main(String args[]) throws JsonProcessingException, IOException {
ObjectMapper mapper = new ObjectMapper();
/**
* Read JSON from a file into a Map
*/
try {
Map<String, Object> map = mapper.readValue(new File(
"result.json"), new TypeReference<Map<String, Object>>() {
});
;
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I stored latitudes and longitudes of all locations in MySQL database. I get the data from database and parse it with jSON. I store all parsed values in HashMap collection. However when I iterate through HashMap collection I can get only last key/value (NOT all of them). What do I need to do in order to get all key/values of each location? Here is my code:
package com.example.maptest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.maps.GoogleMap;
public class ShowAllMarkers {
JSONParser jParser = new JSONParser();
private static String url_all_markers = "http://...............";
JSONParser jsonParser = new JSONParser();
JSONArray markers;
GoogleMap map;
// HashMap<String, String> markersList=new HashMap<String, String>();;
Map<String, String> hMap = new HashMap<String, String>();
public ShowAllMarkers(GoogleMap map) {
this.map = map;
}
public void getAllMarkers() {
new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_markers,
"GET", params);
// in success;
try {
int success = json.getInt("success");
if (success == 1) {
markers = json.getJSONArray("markers");
for (int i = 0; i < markers.length(); i++) {
JSONObject markersObject = markers.getJSONObject(i);
String lat = markersObject.getString("lat");
String longt = markersObject.getString("long");
hMap.put("Latitude", lat);
hMap.put("Longitude", longt);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// Outputs hashmap elements as key and value
Set<Map.Entry<String, String>> set = hMap.entrySet();
for (Map.Entry<String, String> me : set) {
Log.d("JWP", "Key is:" + me.getKey() + ", value is: " + me.getValue());
}
}
}.execute();
}
}
This is my json output:
{
"markers":[
{
"lat":"40.4176083",
"long":"49.9389495",
"title":"Location",
"description":""
},
{
"lat":"40.4175711",
"long":"49.9389274",
"title":"Location",
"description":""
},
{
"lat":"40.4176178",
"long":"49.9389621",
"title":"Location",
"description":""
},
{
"lat":"40.4176178",
"long":"49.9389621",
"title":"Location",
"description":""
},
{
"lat":"40.4176178",
"long":"49.9389621",
"title":"Location",
"description":""
},
{
"lat":"40.4176178",
"long":"49.9389621",
"title":"Location",
"description":""
},
{
"lat":"40.4176178",
"long":"49.9389621",
"title":"Location",
"description":""
},
{
"lat":"40.4176126",
"long":"49.9389561",
"title":"Location",
"description":""
}
],
"success":1
}
Thank you in advance.
I think its the way you use your hashMap.
if markers.length() give more than 1 then means its loading the markers array correctly.
Take a look at these examples, hope it helps
http://java67.blogspot.com.au/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html
According to the interface, its taking in key and value pair. And in your code, you kept replacing the new value with the same key.
Also, to check this, you can find out how many elements are in the hashMap, I would assume you had 1 only.
I would expect something like this
int key=0;
Loop{
hMap.put("Latitude_key"+key, lat);
hMap.put("Longitude_key"+key, longt);
key++;
}
All the best