Consider the following code:
public void testDumpWriter() {
Map<String, Object> data = new HashMap<String, Object>();
data.put("NAME1", "Raj");
data.put("NAME2", "Kumar");
Yaml yaml = new Yaml();
FileWriter writer = new FileWriter("/path/to/file.yaml");
for (Map.Entry m : data.entrySet()) {
String temp = new StringBuilder().append(m.getKey()).append(": ").append(m.getValue()).toString();
yaml.dump(temp, file);
}
}
The output of the above code is
'NAME1: Raj'
'NAME2: Kumar'
But i want the output without the single quotes like
NAME1: Raj
NAME2: Kumar
This thing is very comfortable for parsing the file.
If anyone have solution, please help me to fix. Thanks in advance
Well SnakeYaml does exactly what you tell it to: For each entry in the Map, it dumps the concatenation of the key, the String ": ", and the value as YAML document. A String maps to a Scalar in YAML, and since the scalar contains a : followed by space, it must be quoted (else it would be a key-value pair).
What you actually want to do is to dump the Map as YAML mapping. You can do it like this:
public void testDumpWriter() {
Map<String, Object> data = new HashMap<String, Object>();
data.put("NAME1", "Raj");
data.put("NAME2", "Kumar");
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
FileWriter writer = new FileWriter("/path/to/file.yaml");
yaml.dump(data, writer);
}
Related
If I have the following yaml structure, how can I read it in java efficiently? Currently, I an reading as
xmas-fifth-day:
calling-birds:
value: four
partridges:
count: 1
value: "a pear tree"
turtle-doves:
value: two
Yaml yaml = new Yaml();
InputStream inputStream = new FileInputStream(new File("src/main/resources/customer.yaml"));
Map<String, Object> data = yaml.load(inputStream);
LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, String>>> lhm = (LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, String>>>) data.get("xmas-fifth-day");
Since I am using 3 levels of hashmap, just for the readability purpose, I was wondering if there's a simplified version of this yaml structure to read in less nesting LHM way in java?
EDIT: I don't want to add a POJO here since the config is meant to be dynamic in my use case, where any one can add any config and the code should work without editing the java classes.
It looks like you are using SnakeYAML so you could define custom types:
public class XmasFifthDay {
private CallingBirds callingBirds;
private Partridges partridges;
private TurtleDoves turtle-doves;
// getters and setters
}
public class CallingBirds {
private String value;
// getters and setters
}
// other classes: Partridges, TurtleDoves
and then load it with:
XmasFifthDay data = yaml.load(inputStream);
Perhaps CallingBirds, Partridges, TurtleDoves could be a single class with count and value fields but the example you have provided is not very clear.
As I see it you have better options with Jackson:
Yaml yaml = new Yaml();
InputStream inputStream = new FileInputStream(new File("test.yml"));
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
final JsonNode jsonNode = mapper.readValue(inputStream, JsonNode.class);
System.out.println(jsonNode.toPrettyString());
and the output will be :
{
"xmas-fifth-day" : {
"calling-birds" : {
"value" : "four"
},
"partridges" : {
"count" : 1,
"value" : "a pear tree"
},
"turtle-doves" : {
"value" : "two"
}
}
}
System.out.println(jsonNode.get("xmas-fifth-day"));
{"calling-birds":{"value":"four"},"partridges":{"count":1,"value":"a pear tree"},"turtle-doves":{"value":"two"}}
Also you could have a map of String and JsonNode, using TyperReference
inputStream = new FileInputStream(new File("test.yml"));
final Map<String,JsonNode> map = mapper.readValue(inputStream, new TypeReference<Map<String, JsonNode>>() {});
System.out.println(map.get("xmas-fifth-day"));
and the output is :
{"calling-birds":{"value":"four"},"partridges":{"count":1,"value":"a pear tree"},"turtle-doves":{"value":"two"}}
I try to write a json file and I want to get an output like this:
{"key1" : "value"..}
{"key4" : "value"..}
in the same file.
I've done it this way:
public class Writer {
public void writerMeth(String[] dataArray) throws IOException{
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("key1",dataArray[0])
.add("key2",dataArray[1])
.add("key3",dataArray[2]) ;
JsonStructure output=builder.build();
HashMap<String, Object> config = new HashMap<String, Object>();
config.put(JsonGenerator.PRETTY_PRINTING, true);
JsonWriterFactory factory =Json.createWriterFactory(config);
JsonWriter writer = factory.createWriter(new FileOutputStream("file.json"));
writer.write(output);
writer.close();
My problem is that by calling the method the old data is deleted; I want to write the next entry at the next free line. It is possible?
I have the Yaml file:
#Define CDN domains
---
CDN:
quality: 200..300
cost: low
Video-type: mp4
and with this Java code, I retrieve sub values of CDN:
// The path of your YAML file.
Yaml yaml = new Yaml();
Map<String, Map<String, String>> values =
(Map<String, Map<String, String>>) yaml
.load(new FileInputStream(new File("/workspace/servlet-yaml/src/test.yaml")));
for (String key : values.keySet()) {
Map<String, String> subValues = values.get(key);
for (String subValueKey : subValues.keySet()) {
System.out.println(values);
}
}
The output is:
{CDN={quality=200..300, cost=low, Video-type=mp4}}
{CDN={quality=200..300, cost=low, Video-type=mp4}}
{CDN={quality=200..300, cost=low, Video-type=mp4}}
First of all, I don't know why it repeats three times?
Secondly, I want to write a code that
if cost = low , then do somthing.
First of all, I dont know whay it reapets three times?
Because you tell it to. For each subValueKey, print the whole value set. There are three sub-keys, so the complete value set gets printed three times.
Secondly, I want to write a code that if cost = low , then do somthing.
Yaml yaml = new Yaml();
Map<String, Map<String, String>> values =
(Map<String, Map<String, String>>) yaml.load(
new FileInputStream(new File(
"/workspace/servlet-yaml/src/test.yaml")));
final Map<String, String> cdn = values.get("CDN");
// or iterate over all keys like you currently do
final String cost = cdn.get("cost");
// or iterate over all subkeys and compare them to "cost".
// that way, it's easier to handle missing keys.
if ("low".equals(cost)) {
// do something
}
I try to make this json format:
[{"x":1392440400000,"title":"!"},{"x":1392465600000,"title":"!"}]
I tried it out with the jsonGenerator
This is my code:
JsonFactory f = new JsonFactory();
StringWriter sw = new StringWriter();
JsonGenerator g = f.createJsonGenerator(sw);
while {
g.writeStartObject();
g.writeNumberField("x",111111);
g.writeStringField("title","!");
g.writeEndObject();
}
g.close();
return "["+sw.toString()+"]";
But my output is like that ist like that:
[{"x":1392440400000,"title":"!"} {"x":1392465600000,"title":"!"}]
Can anybody help me to make the correct Json output with a comma between the objects ?
You can use the ObjectMapper to generate the output.
So this could be something like this.
ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("x", 1392440400000l);
data.put("title", "!");
HashMap<String, Object> data2 = new HashMap<String, Object>();
data2.put("x", 1392440400000l);
data2.put("title", "!");
List out = new ArrayList();
out.add(data);
out.add(data2);
String val = mapper.writeValueAsString(out);
I'm not using jackson, but for this specific scenario, you need your g.writeStartObject(); and g.writeEndObject(); inside the loop. (Because you're essentially trying to create an Array of Objects, right?)
Have tried to search for this almost 'everywhere', but couldn't find a pointer as to how to implement this. Please kindly review my code and offer suggestions on how to set/update ALL documents properties in SharePoint using OpenCMIS. Have created the documents successfully using CMIS, however I'm not able to populate different values for different documents.
For example, a.pdf, b.pdf have different properties. So when I update them, i expect the value to be mapped from array of values assigned to them but at the moment, the same value are being append to all the documents...
Please see my code below, hopefully it will make things clearer:
try {
String [] nextLine =null;
CSVReader reader = new CSVReader(new FileReader(indexFileLocation));
List content = reader.readAll();
for (Object o : content) {
nextLine = (String[]) o;
System.out.println("\n"+ nextLine[2] + "\n"+nextLine[7] + "\n"+ nextLine[6]);
}
//reader.close();
Map <String, Object> newDocProps = new HashMap<String, Object>();
newDocProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
newDocProps.put(PropertyIds.NAME, ff.getName());
Document doc = newFolder.createDocument(newDocProps, contentStream, VersioningState.NONE);
CmisObject cmisobject = (Document) session.getObject(doc.getId());
Map<String, Object> pp = new HashMap<String, Object>();
//pp.put(PropertyIds.OBJECT_ID, "Name");
pp.put("WorkflowNumber", nextLine[7]);
pp.put("InvoiceDate", nextLine[2]);
cmisobject.updateProperties(pp);
Any help is appreciated.
#Albert, How are you creating session? It could be an issue with session creation. Please paste your code here to create session.