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]
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 parse the content of JSON file text.json by using Jackson library.
What I want is to make a java method in the following code to get all keys and values of it, but so far in my code I get only the first key and the first value of the JSON file.
Here is my Java class:
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonStreamExample {
public static void main(String[] args) {
try {
//Create a JsonFactory instance
JsonFactory factory = new JsonFactory();
//Create a JsonParser instance to read from file c:\\text.json
JsonParser jParser = factory.createJsonParser(new File("c:\\text.json"));
/*Create an ObjectMapper instance to provide a pointer
* to root node of the tree after reading the JSON
*/
ObjectMapper mapper = new ObjectMapper(factory);
//Create tree from JSON
JsonNode rootNode = mapper.readTree(jParser);
Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.getFields();
while (fieldsIterator.hasNext()) {
Map.Entry<String,JsonNode> field = fieldsIterator.next();
System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
jParser.close();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My Eclipse output is the following which creates only 1 pair(key-value):
Key: cells Value:[{"type":"basic.Circle","size":{"width":90,"height":54},"position":{"x":-80,"y":200},"angle":0,"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24","embeds":"","z":1,"wi_name":"START","wi_displayName":"START","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"circle":{"fill":"#000000","width":50,"height":30,"stroke-width":1,"stroke-dasharray":"0"},"text":{"font-size":10,"text":"START","fill":"#ffffff","font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Circle","size":{"width":90,"height":54},"position":{"x":210,"y":200},"angle":0,"id":"d23133e0-e516-4f72-8127-292545d3d479","embeds":"","z":2,"wi_name":"END","wi_displayName":"END","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"circle":{"fill":"#000000","width":50,"height":30,"stroke-width":1,"stroke-dasharray":"0"},"text":{"font-size":10,"text":"END","fill":"#ffffff","font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Rect","position":{"x":-80,"y":370},"size":{"width":90,"height":54},"angle":0,"id":"a53898a5-c018-45c4-bd3f-4ea4d69f58ed","embeds":"","z":3,"wi_name":"ACTIVITY_1","wi_displayName":"ACTIVITY 1","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"rect":{"width":50,"height":30,"rx":2,"ry":2,"stroke-width":1,"stroke-dasharray":"0"},"text":{"text":"Activity","font-size":10,"font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Rect","position":{"x":220,"y":370},"size":{"width":90,"height":54},"angle":0,"id":"e2bd21f2-508d-44b9-9f68-e374d4fa87ea","embeds":"","z":4,"wi_name":"ACTIVITY_2","wi_displayName":"ACTIVITY 2","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"rect":{"width":50,"height":30,"rx":2,"ry":2,"stroke-width":1,"stroke-dasharray":"0"},"text":{"text":"Workitem","font-size":10,"font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"link","source":{"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24"},"target":{"id":"d23133e0-e516-4f72-8127-292545d3d479"},"router":{"name":"manhattan"},"labels":[{"position":0.5,"attrs":{"text":{"text":"Name"}}}],"id":"60ee7ff7-3a3b-487d-b581-49027e7bebe4","embeds":"","z":5,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"},".connection":{"stroke":"black"}}},{"type":"link","source":{"id":"a53898a5-c018-45c4-bd3f-4ea4d69f58ed"},"target":{"id":"e2bd21f2-508d-44b9-9f68-e374d4fa87ea"},"router":{"name":"manhattan"},"labels":[{"position":0.5,"attrs":{"text":{"text":"Name"}}}],"id":"cea0d1c2-2c18-4bd7-ba35-d94918c6fc9b","embeds":"","z":6,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"},".connection":{"stroke":"black"}}}]
How will I do it please?
In the above code sample, the nested/Hierarchical Structure is not considered of json value and it directly prints it as field.getValue().
You'll have to check for the type of value using
if(field.getValue().isObject())
{
parse(field.getValue())
}
The Parse Method could be as follows
private void parse(JsonNode jsonNode)
{
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = jsonNode.getFields();
while (fieldsIterator.hasNext())
{
Map.Entry<String, JsonNode> field = fieldsIterator.next();
if (field.getValue().isObject())
{
parse(field.getValue());
}
System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
}
Then you have to just call the parse method for the rootNode.
I solved my problem by changing JSON library.
I used json-simple-1.1.1
My final code that worked is the following:
package jsontoxml;
import java.io.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.*;
import java.util.*;
public class JacksonStreamExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("text.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray cells = (JSONArray) jsonObject.get("cells");
Iterator<JSONObject> iterator = cells.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using yamlbeans to get data from yaml file. i am getting following response
{x1=[{y1=z1}, {y2=z2}], x2=[{y1 =z1}, {y2=z2]}
Now i want to get data y1 of x1 but i am not able to do this. I am using following code for read operation
package com.mobileapp;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import net.sourceforge.yamlbeans.YamlReader;
public class ReadDataWithYaml {
public static void main(String[] args) {
try {
YamlReader reader = new YamlReader(new FileReader("C:\\Users\\5521\\Desktop\\test.yml"));
Object object = reader.read();
System.out.println(object);
Map<String, ArrayList<String>> map = (Map<String, ArrayList<String>>) object;
System.out.println(map.get("x1"));
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Yaml yaml1 = new Yaml();
InputStream inputStream1 = Main.class.getClassLoader().getResourceAsStream("YourYaml.yaml");
Map< String, Object> result = (Map< String, Object>) yaml1.load(inputStream1);
for (Object name : result.keySet()) {
System.out.println(result.get(name).toString());
}
String x= result.get("userInput").toString();
System .out.println(""+x);