Java - Parse Yaml to Json - java

Python and Ruby have very nice libraries for parsing a Yaml file into a JSON object.
The parser needs to support Yaml Anchor and References.
Input
info: &info
legs: 4 legs
type: pet
dog: *info
cat: *info
Desired output:
{
"info": {
"legs": "4 legs",
"type": "pet"
},
"dog": {
"legs": "4 legs",
"type": "pet"
},
"cat": {
"legs": "4 legs",
"type": "pet"
}
}
I first tried the Jackson YAMLFactory. That library did not generically support anchors and references.
What is a good solution in Java for parsing Yaml into a JSON object?

The following solution seemed to work.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.yaml.snakeyaml.Yaml;
public class YamlParser {
public static void main(String[] argv) {
File f = new File("my.yml");
final Yaml yaml = new Yaml();
try {
final Object loadedYaml = yaml.load(new FileReader(f));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(loadedYaml,LinkedHashMap.class);
System.out.println(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
With the following maven dependencies.
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.21</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>

Related

Java creating json from translation key value pairs

I have a sorted list (by key) of key value pairs like this:
administration.edit.error.type1 = val1
administration.edit.error.type2 = val2
administration.edit.success.type1 = val3
administration.label.button.close = val4
administration.label.button.edit = val5
home.label.button.open = val6
I would want to convert this list to
{
"administration": {
"edit": {
"error": {
"type1": val1,
"type2": val2,
},
"success": {
"type1": val3
}
},
"label": {
"button": {
"close": val4,
"edit": val5,
}
}
},
"home": {
"label": {
"button": {
"open": val6
}
}
}
}
The provided input list is unknown, as well as the levels connected by the dots
My approach would have been to recursively, iterate through the list and create JsonNodes with Jackson mapper. Is there a more efficient way to do this? Is there maybe a library that can already do this?
JavaPropsMapper, from jackson-dataformat-properties does the job
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
public class Application {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("/tmp/test.properties");
Properties properties = new Properties();
properties.load(fr);
HashMap map = new JavaPropsMapper().readPropertiesAs(properties, HashMap.class);
System.out.println(map);
String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);
}
}
Output for your sample-file:
{administration={edit={error={type2=val2, type1=val1}, success={type1=val3}}, label={button={close=val4, edit=val5}}}, home={label={button={open=val6}}}}
{"administration":{"edit":{"error":{"type2":"val2","type1":"val1"},"success":{"type1":"val3"}},"label":{"button":{"close":"val4","edit":"val5"}}},"home":{"label":{"button":{"open":"val6"}}}}
The sample uses these dependencies:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-properties</artifactId>
<version>2.11.1</version>
</dependency>

Is there a way to serialise Java TreeMap into a JSON?

I have a Java TreeMap frutitas inside a custom object on the server side which I want to send to the frontend.
I use javax.ws and jackson to serialise. The data that I get in the frontend looks like this:
{ "frutitas": {
"entry": [
{
"key": "fruto 1",
"value": "el banano"
},
{
"key": "fruto 2",
"value": "el pineapple"
}
]
}
But I want to get something like this, which is actually how I send the "frutitas" map inside the object that I send to the backend when I want to upload it:
{
"frutitas": {
"fruto 1": "el banano",
"fruto 2": "el pineapple"
}
}
Another option is to use gson.
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
And the class containing the map:
public class FrutitasClass {
private Map<String, String> frutitas;
}
The code below would the conversion:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(frutitasClassObject);
Out:
{
"frutitas": {
"fruto 1": "el banano",
"fruto 2": "el pineapple"
}
}
You can convert TreeMap to JSONObject as you expected. Here is the sample so that you can get the idea.
JSONObject jsonObject = new JSONObject(yourTreeMap);
If you print jsonObject, Output will be like this.
{"fruto 1":"el banan","fruto 2":"el pineapple"}
JSONObject main = new JSONObject();
main.put("frutitas", jsonObject);
{
"frutitas": {
"fruto 1": "el banano",
"fruto 2": "el pineapple"
}
}
Library Json-Jackson also known as FasterXML is de-facto standard for JSON serialization-deserialization. It works fast and is widely used. Below is a simple class that I wrote for serializing/de-serializing any Object. But in general you need to look at ObjectMapper class to see how it works. Here is Github link to a project. Here are Maven dependencies you may use:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.9</version>
</dependency>
My Class Example
package com.bla.json.utils;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
public class JsonUtil {
private static final ObjectReader objectReader;
private static final ObjectWriter objectWriter;
static {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModules(new JavaTimeModule());
objectMapper.enableDefaultTyping();
objectReader = objectMapper.reader();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectWriter = objectMapper.writer();
}
public static String writeObjectToJsonString(Object object) throws JsonProcessingException {
String jsonData = null;
if (object != null) {
jsonData = objectWriter.writeValueAsString(object);
}
return jsonData;
}
public static <T> T readObjectFromJsonString(String s, Class<T> type) throws IOException {
T data = objectReader.forType(type).readValue(s);
return data;
}
}

Parse csv data and convert to nested json java

I'm searching for simplest way or any jar available to read csv file in java and convert to into nested json. I tried searching for various sources, but all the places i could find results for simple json, but my need is i should read csv file which later has to be converted to json string in the below format
{
"studentName": "Foo",
"Age": "12",
"address":{
"city" : "newyork",
"address1": "North avenue",
"zipcode" : "123213"
},
"subjects": [
{
"name": "English",
"marks": "40"
},
{
"name": "History",
"marks": "50"
}
]
}
I'm fine with any format in csv, however after reading csv file i need to create json string like above.
csv file format:
"studentName","Age","address__city","address__address1","address__zipcode","subjects__name","subjects__marks"
"Foo","12","newyork","North avenue","123213","English","40"
"","","","","","History","50"
You can use JackSon to convert CSV to JSON. For example see the following code:
import java.io.File;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
public class CSV2JSON {
public static void main(String[] args) throws Exception {
File input = new File("input.csv");
File output = new File("output.json");
CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();
CsvMapper csvMapper = new CsvMapper();
// Read data from CSV file
List<object> readAll = csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll();
ObjectMapper mapper = new ObjectMapper();
// Write JSON formated data to output.json file
mapper.writerWithDefaultPrettyPrinter().writeValue(output, readAll);
// Write JSON formated data to stdout
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(readAll));
}
}
If you are using maven you can add the Jackson dependency as following:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>2.8.9</version>
</dependency>

XML to JSON Conversion with Conditions

Wanted to covert an xml String to Json and I am doing it as below.
XML which has to be converted
<Item>
<Property name="Description" value="Description 1"/>
<Property name="EffDate" value="01/05/2017"/>
<Property name="ExpDate" value="12/31/9999"/>
<Property name="Status" value="Launched"/>
</Item>
I have created a Class for the xml as below.
public class Context {
#XmlElement(name = "Item")
private List<Item> offer;
}
public class Item {
#XmlElement(name = "Property")
private List<Property> properties;
}
public class Property {
#XmlAttribute
private String name;
#XmlAttribute
private String value;
}
I am using Gson libraries to convert this Java object to Json - g.toJson.
Comverted JSON -
"offer": [{
"properties": [{
"name": "Description",
"value": "Description 1"
},
{
"name": "EffDate",
"value": "01/05/2017"
},
{
"name": "ExpDate",
"value": "12/31/9999"
},
{
"name": "Status",
"value": "Launched"
}]
}]
But we wanted to convert the JSON as below -
"offer": [{
"Description" : "Description 1",
"EffDate":"01/05/2017",
"ExpDate": "12/31/9999",
"Status": "Launched"
}]
Is there a way to convert the properties name and value as Item class properties.?
Try using this link: https://github.com/stleary/JSON-java This is a JSON Helper class that can convert XML to JSON for example:
public class Main {
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING =
"<?xml version=\"1.0\" ?><test attrib=\"moretest\">Turn this to JSON</test>";
public static void main(String[] args) {
try {
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
} catch (JSONException je) {
System.out.println(je.toString());
}
}
}
Hope this helps :)
It is possible using FasterXML library. where you can write your custom logic for generating XML and JSON. By overriding serialize of JsonSerializer class.
Need to write Serializer like :
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
public class ContextSerializer extends JsonSerializer<Context> {
#Override
public void serialize(Context t, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {
jg.writeStartObject();
jg.writeArrayFieldStart("offer");
for (Item i : t.offer) {
jg.writeStartObject();
for (Property property : i.properties) {
jg.writeStringField(property.name, property.value);
}
jg.writeEndObject();
}
jg.writeEndArray();
jg.writeEndObject();
}
}
For convert:
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBException;
public class Main {
public static void main(String[] args) throws JAXBException, JsonProcessingException {
Context c = new Context();
List<Item> offer = new ArrayList<>();
Item pr = new Item();
pr.properties = new ArrayList<>();
Property p = new Property();
p.name = "asdf";
p.value = "va1";
pr.properties.add(p);
p = new Property();
p.name = "asdf1";
p.value = "va11";
pr.properties.add(p);
offer.add(pr);
c.offer = offer;
try {
SimpleModule module = new SimpleModule();
module.addSerializer(Context.class, new ContextSerializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
objectMapper.setSerializationInclusion(Include.NON_DEFAULT);
String json = objectMapper.writeValueAsString(c);
System.out.println(json);
} catch (Exception e) {
System.out.println(""+e);
}
}
}
O/P JSON : (Provided O/P JSON is wrong in your question if you give the name to the list("offer") then it always inside object link)
{
"offer": [{
"asdf": "va1",
"asdf1": "va11"
}
]
}
Maven Dependency for package is:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0.pr3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0.pr3</version>
</dependency>
If you are using Java 8 or later, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.
It's available on Maven Central.
Example
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nerdforge.unxml.factory.ParsingFactory;
import com.nerdforge.unxml.parsers.Parser;
import org.w3c.dom.Document;
public class Parser {
public ObjectNode parseXml(String xml){
Parsing parsing = ParsingFactory.getInstance().create();
Document document = parsing.xml().document(xml);
Parser<ObjectNode> parser = parsing.obj("/")
.attribute("offer", parsing.arr("/Item")
.attribute("Description", "Property[#name='Description']/#value")
.attribute("EffDate", "Property[#name='EffDate']/#value")
.attribute("ExpDate", "Property[#name='ExpDate']/#value")
.attribute("Status", "Property[#name='Status']/#value")
)
.build();
ObjectNode result = parser.apply(document);
return result;
}
}
It will return a Jackson ObjectNode, with the following json:
{
"offer": [
{
"Status": "Launched",
"Description": "Description 1",
"ExpDate": "12/31/9999",
"EffDate": "01/05/2017"
}
]
}
You may convert xml to a map, modify it and then convert to a json. Underscore-java library has static methods U.fromXml(xml) and U.toJson(json). I am the maintainer of the project.

How do I get value from JSON using JsonPath in Java?

I want to get the value from the JSON object using JsonPath.Could anyone please suggest me the appropriate jars which i would need because as per my knowledge i am getting this exception for the jars i am using for jsonpath .
package jsonPg;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import com.jayway.jsonpath.JsonPath;
public class ReadJsonPath {
static String file = "D:\\AutomationSample\\Sample_Json.txt";
public static void main(String[] args) throws JSONException, IOException {
JsonReadFile jsonReadFile=new JsonReadFile();
JSONObject jsonObj=jsonReadFile.parseJSONFile(file);
String jsonObject=jsonObj.toString();
String json="";
System.out.println(jsonObject);
// Object val = JsonPath.read(jsonObject,"");
String val1=JsonPath.read(jsonObject," $.payload[*].supplierDataMap[*].COMPANYDETAILS.customFieldList[*].DISPLAYGSID .value");
System.out.println(val1);
}
}
here is the code which i have written and below is the exception which is thrown at runtime
Exception in thread "main" java.lang.NoSuchFieldError: FACTORY_SIMPLE
at com.jayway.jsonpath.spi.impl.JsonSmartJsonProvider.<init>(JsonSmartJsonProvider.java:38)
at com.jayway.jsonpath.spi.impl.JsonSmartJsonProvider.<init>(JsonSmartJsonProvider.java:41)
at com.jayway.jsonpath.spi.JsonProviderFactory.<clinit> (JsonProviderFactory.java:24)
at com.jayway.jsonpath.Configuration.defaultConfiguration(Configuration.java:62)
at com.jayway.jsonpath.internal.JsonReader.<init>(JsonReader.java:26)
at com.jayway.jsonpath.JsonPath.read(JsonPath.java:462)
at jsonPg.ReadJsonPath.main(ReadJsonPath.java:27)`
Any kind of help would be appreciated .
Thanks in advance .
You can achieve your goal with JsonPath library on its own. Here is an example:
String jsonString = "{ \"list\": [ { \"name\": \"foo1\"}, { \"name\": \"foo2\"} ]}";
DocumentContext docCtx = JsonPath.parse(jsonString);
JsonPath jsonPath = JsonPath.compile("$.list[?(#.name == \"foo1\")]");
JSONArray val1=docCtx.read(jsonPath);
System.out.println(val1);
This code will print out:
[{"name":"foo1"}]
Required maven dependency:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
json-path will also automatically pull json-smart JAR:
<dependency>
<groupId>net.minidev</groupId>
<artifactId>json-smart</artifactId>
<version>2.2.1</version>
</dependency>
String jsonString = "{ \"list\": [ { \"name\": \"foo1\"}, { \"name\": \"foo2\"} ]}";
DocumentContext docCtx = JsonPath.parse(jsonString);
JsonPath jsonPath = JsonPath.compile("$.list[?(#.name == foo1)]");
JSONArray val1=docCtx.read(jsonPath);
System.out.println(val1);

Categories