How do I get value from JSON using JsonPath in Java? - 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);

Related

JSON response from string in Javalin

I am trying to create the response in JSON format from a string in Javalin. JSON object must be from a string, not from class.
public static void main(String[] args) {
Javalin app = Javalin.create().start(9000);
String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}";
JsonObject jsonObject= JsonParser.parseString(jsonString).getAsJsonObject();
app.error(404, ctx -> ctx.json(jsonObject));
...
}
With the code above, I am getting a 500 server error.
If you are using Gson, then switch to using Jackson, when using Javalin methods such as ctx.json().
If you used Maven to import Javalin, and if you used the javalin-bundle, then you will already have Jackson, for example:
<dependency>
<groupId>io.javalin</groupId>
<artifactId>javalin-bundle</artifactId>
<version>3.13.3</version>
</dependency>
If you only used javalin and not javalin-bundle then you will need to add Jackson yourself - for example:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
</dependency>
The following is the code from the question, but re-worked to use Jackson (and to use valid JSON):
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.javalin.Javalin;
public class App {
public static void main(String[] args) throws JsonProcessingException {
Javalin app = Javalin.create().start(9000);
String jsonString = "{\"test1\":\"value1\",\"test2\":{\"id\":0,\"name\":\"testName\"}}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
app.error(404, ctx -> ctx.json(jsonNode));
}
}

Java - Parse Yaml to Json

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>

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;
}
}

How to convert a Java object to JSON object in Eclipse

My requirement is to convert a plain Java object to JSON format -
The Java object has following format -
Record Id: 168349200
Name: jane
City: abababa
State: ababab
Insertion Date: 18/04/2017 10:16:17
I have gone through some tutorials and found that GSON library is a way to do it. I tried to install the gson jar in my Eclipse project (using Eclipse Mars Release (4.5.0)).
But when I do -
import com.google.gson.Gson
in the class where I want to do the conversion of the Java object to JSON it throws an exception.
I think I have not added the GSON jar file properly.
Can some one please help.
Thanks.
Try:
Gson gson = new Gson();
String jsonString = null;
try {
jsonString = gson.toJson(javaObject);
} catch (Exception e) {
e.printStackTrace();
}
From Java Object to Json using ObjectMapper:
ObjectMapper objMapper = new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
MyObject mObject = new MyObject();
String jsonObject ="";
mObject.setField1(value1);
mObject.setField2(value2);
mObject.setField3(value3);
try {
jsonObject = objMapper.writeValueAsString(mObject);
System.out.println(jsonObject); //You can then store it in a file
} catch (JsonProcessingException e) {
e.printStackTrace();
}
You should add these imports:
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
And in the pom.xml these lines:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.5</version>
</dependency>

convert json data to csv data using java

If our JSON data consists only of flat, one-dimensional data,
how can convert those data by iterating over your outer objects and building a CSV line by concating the string values of your inner objects.
Could anyone provide with example please?
You can try this :
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class toCSV {
public static void main(String args[]){
String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}"
JSONObject output = new JSONObject(jsonString);
JSONArray docs = response.getJSONArray("infile");
File file=new File("C:/JsontoCSVExample.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
}
}
The maven dependency was like,
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
Also, You can take ref. from here

Categories