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));
}
}
Related
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;
}
}
I am trying to convert JSON to XML in middle ware tool. I am using Jackson libraries to do this transformation. The problem is that for decimal fields (length more than 8) in JSON, the corresponding XML value is converted to scientific notation. For example 8765431002.13 is converted to 8.76543100213E8.
I can convert the scientific notation to normal decimal format if know the name of the field. But in my case, the middleware application will not be aware of field that is coming as decimal.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class JSONDataformat {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//String jsonString = "{\"Field1\":18629920.68,\"Field3\":\"test\", \"Field2\":\"null\"}";
ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper xmlMapper = new XmlMapper();
JsonNode tree = objectMapper.readTree(jsonString);
String jsonAsXml = xmlMapper.writer().writeValueAsString(tree);
System.out.println(jsonAsXml);
}
catch(Exception e) {e.printStackTrace(); }
}
}
Output
<ObjectNode xmlns=""><Field1>1.862992068E7</Field1><Field3>test</Field3><Field2/></ObjectNode>
I expected to get <Field1> value as 18629920.68 in above code.
You need to enable USE_BIG_DECIMAL_FOR_FLOATS feature:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
EDIT
import com.fasterxml.jackson.core.JsonGenerator.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
String jsonString = "{\"Field1\": 20121220.00,\"Field3\":\"test\", \"Field2\":\"null\"}";
ObjectMapper jsonMapper = new ObjectMapper();
jsonMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
XmlMapper xmlMapper = new XmlMapper();
JsonNode tree = jsonMapper.readTree(jsonString);
String jsonAsXml = xmlMapper.writer().with(Feature.WRITE_BIGDECIMAL_AS_PLAIN).writeValueAsString(tree);
System.out.println(jsonAsXml);
}
}
Above code prints:
<ObjectNode><Field1>20121220</Field1><Field3>test</Field3><Field2>null</Field2></ObjectNode>
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>
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);
I have web-service in .net. When I retrieve data from database, it returns JSON File in Android Mobile. How can I convert JSON File to XML Or text.
For a simple solution, I recommend Jackson, as it can transform arbitrarily complex JSON into XML with just a few simple lines of code.
import org.codehaus.jackson.map.ObjectMapper;
import com.fasterxml.jackson.xml.XmlMapper;
public class Foo
{
public String name;
public Bar bar;
public static void main(String[] args) throws Exception
{
// JSON input: {"name":"FOO","bar":{"id":42}}
String jsonInput = "{\"name\":\"FOO\",\"bar\":{\"id\":42}}";
ObjectMapper jsonMapper = new ObjectMapper();
Foo foo = jsonMapper.readValue(jsonInput, Foo.class);
XmlMapper xmlMapper = new XmlMapper();
System.out.println(xmlMapper.writeValueAsString(foo));
// <Foo xmlns=""><name>FOO</name><bar><id>42</id></bar></Foo>
}
}
class Bar
{
public int id;
}
This demo uses Jackson 1.7.7 (the newer 1.7.8 should also work), Jackson XML Databind 0.5.3 (not yet compatible with Jackson 1.8), and Stax2 3.1.1.
Here is an example of how you can do this, generating valid XML. I also use the Jackson library in a Maven project.
Maven setup:
<!-- https://mvnrepository.com/artifact/com.fasterxml/jackson-xml-databind -->
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>jackson-xml-databind</artifactId>
<version>0.6.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>
Here is some Java code that first converts a JSON string to an object and then converts the object with the XMLMapper to XML and also removes any wrong element names. The reason for replacing wrong characters in XML element names is the fact that you can use in JSON element names like $oid with characters not allowed in XML. The Jackson library does not account for that, so I ended up adding some code which removes illegal characters from element names and also the namespace declarations.
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.xml.XmlMapper;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Converts JSON to XML and makes sure the resulting XML
* does not have invalid element names.
*/
public class JsonToXMLConverter {
private static final Pattern XML_TAG =
Pattern.compile("(?m)(?s)(?i)(?<first><(/)?)(?<nonXml>.+?)(?<last>(/)?>)");
private static final Pattern REMOVE_ILLEGAL_CHARS =
Pattern.compile("(i?)([^\\s=\"'a-zA-Z0-9._-])|(xmlns=\"[^\"]*\")");
private ObjectMapper mapper = new ObjectMapper();
private XmlMapper xmlMapper = new XmlMapper();
String convertToXml(Object obj) throws IOException {
final String s = xmlMapper.writeValueAsString(obj);
return removeIllegalXmlChars(s);
}
private String removeIllegalXmlChars(String s) {
final Matcher matcher = XML_TAG.matcher(s);
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
String elementName = REMOVE_ILLEGAL_CHARS.matcher(matcher.group("nonXml"))
.replaceAll("").trim();
matcher.appendReplacement(sb, "${first}" + elementName + "${last}");
}
matcher.appendTail(sb);
return sb.toString();
}
Map<String, Object> convertJson(String json) throws IOException {
return mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
}
public String convertJsonToXml(String json) throws IOException {
return convertToXml(convertJson(json));
}
}
Here is a JUnit test for convertJsonToXml:
#Test
void convertJsonToXml() throws IOException, ParserConfigurationException, SAXException {
try(InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("json/customer_sample.json")) {
String json = new Scanner(in).useDelimiter("\\Z").next();
String xml = converter.convertJsonToXml(json);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
Node first = doc.getFirstChild();
assertNotNull(first);
assertTrue(first.getChildNodes().getLength() > 0);
}
}
No direct conversion API is available in android to convert JSON to XML. You need to parse JSON first then you will have to write logic for converting it to xml.
Standard org.json.XML class converts between JSON and XML in both directions. There is also tutorial on how to use it.
The conversion is not very nice as it does not create XML attributes at all (entities only), so XML output is more bulky than could possibly be. But it does not require to define Java classes matching the data structures that need to be converted.
Underscore-java library has static method U.jsonToXml(string). Live example
import com.github.underscore.U;
public class MyClass {
public static void main(String args[]) {
String json = "{\"Price\": {"
+ " \"LineItems\": {"
+ " \"LineItem\": {"
+ " \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
+ " }"
+ " },"
+ " \"Currency\": \"USD\","
+ " \"EnterpriseCode\": \"EnterpriseCode\""
+ "}}";
System.out.println(U.jsonToXml(json));
}
}
Output:
<?xml version="1.0" encoding="UTF-8"?>
<Price>
<LineItems>
<LineItem>
<UnitOfMeasure>EACH</UnitOfMeasure>
<Quantity number="true">2</Quantity>
<ItemID>ItemID</ItemID>
</LineItem>
</LineItems>
<Currency>USD</Currency>
<EnterpriseCode>EnterpriseCode</EnterpriseCode>
</Price>