Can someone point me to the correct way to convert xml into json with jackson?
I have one service that accepts a post request with an xml body, I want to take that xml and send it to another service as a json.
I've seen some examples where people use an ObjectMapper, but ideally, I would have an interface ModelJsonView and then use the setMixInAnnotation() method to bind it to the corresponding model class.
Try this:
String xml = "<testName>Tester</testName><testValue>100</testValue>"
JSONObject xmlToJsonObject = XML.toJSONObject(xml);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
Object json = mapper.readValue(xmlToJsonObject.toString(), Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
Include org.json and jackson jars.
Related
I have a JSON string from response to REST API which I am trying to deserialize into an ObjectNode in Jackson like below.
String response = webservice(...);
ObjectNode jsonObj = new ObjectMapper().readTree(response);
In our static scan of the source code, it found vulnerability to JSON injection that this call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.
How can I make sure to protect against JSON injection?
I have a POJO object that has UpperCamelCase naming. When I do the call to Jackson's ObjectMapper to serialize/marshal it to JSON, the result is lowerCamelCase for field names.
The call is now trivial:
Heading
ObjectMapper objectMapper = new ObjectMapper();
jsonText = objectMapper.writeValueAsString(myObjectToJson);
how I can tell ObjectMapper to make UpperCamelCase? Or is it some sort of set-in-stone JSON standard?
I use jackson inside Apache Camel.
edited original answer.
Jackson uses camelCasing as default it seems. They have implemented a PascalCasing strategy. Try this:
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE);
Or annotate your fields with #JsonProperty("UpperCaseProperty")
I have a restful web service(JAVA) which has to accept JSON requests. I have to first validate this JSON against a JSON schema that I have.
I'm not sure what is the best JAVA library to validate JSON again JSON schemas.
I have used json-schema-validator-2.1.7 library but it has not been very helpful. Even thought my JSON is not a valid JSON I do not get any errors.
Here is the code I use for json-schema-validator-2.1.7
InputStream jsonSchemaInputStream = Assessment.class.getClassLoader().getResourceAsStream("Schemas/AssessmentMetrics.json");
ObjectMapper mapper = new ObjectMapper();
// Allows to retrieve a JSONSchema object on various sources
// supported by the ObjectMapper provided
JSONSchemaProvider schemaProvider = new JacksonSchemaProvider(mapper);
// Retrieves a JSON Schema object based on a file
JSONSchema schema = schemaProvider.getSchema(jsonSchemaInputStream);
// Validates a JSON Instance object stored in a file
List<String> errors = schema.validate(contents);
Projects worth exploring:
https://github.com/java-json-tools/json-schema-validator
https://github.com/everit-org/json-schema
https://github.com/networknt/json-schema-validator
Here is a nice list.
Here is an online sandbox.
I'm biased with jackson for all things JSON.
https://github.com/FasterXML/jackson-module-jsonSchema
I am developing a web application. I have database used by the web service. I want to send the same data to the web pages which are calling web service.
I get the data i.e. single row from the database by using hibernate and POJO classes(getColumn). Now I have object(POJO class) of the Table which represent single row of the database. For sending it back to the web pages (html, jsp), I need to convert it to the json object as my web service returns the json object.
How can I make Json object from POJO classes. There are many other ways to generate Json String but i want json object.
How can do this?
Thank you
You can use GSon to convert json object to java object
Link
to refer example.
Gson gson = new Gson();
//to get json object use toJson
String json = gson.toJson(obj);
//to get java object use fromJson
MyClass obj = gson.fromJson(jsonObj, MyClass.class);
or
jackson is also pretty fast and easy to use
private ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.convertValue(YOUR POJO CLASS, JsonNode.class);
You can use Jackson and achieve this as above. GSON also does the job.
The way I use is with Google's Gson library. Very simple and powerful
Spring and Jackson as it is so simple. You can find a very basic example below Jackson/spring JSON example
I've started using Jackson as a JSON generator, as an alternative to google GSON. I've run into an issue where Jackson is generating object: null if the object is indeed null. GSON on the other hand generates NO entry in JSON, which is the behavior I want. Is there a way to stop Jackson from generating null object/value when an object is missing?
Jackson
ObjectMapper mapper = new ObjectMapper();
StringWriter sw = new StringWriter();
mapper.writeValue(sw, some_complex_object);
String jackson = sw.getBuffer().toString();
System.out.println("********************* START JACKSON JSON ****************************");
System.out.println(jackson);
System.out.println("********************* END JACKSON JSON ****************************");
generates this:
{"eatwithrustyspoon":{"urlList":null,"device":"iPad","os":"iPhone OS","peer_id":
and GSON looks like this:
Gson gson = new Gson();
String json = gson.toJson(some_complex_object);
System.out.println("********************* START GSON JSON ****************************");
System.out.println(json);
System.out.println("********************* END GSON JSON ****************************");
and it generates this (which is what I want - note that "urlList":null was not generated) :
{"eatwithrustyspoon":{"device":"iPad","os":"iPhone OS","peer_id"
From the Jackson FAQ:
Can I omit writing of Bean properties with null value? ("how to prevent writing of null properties", "how to suppress null values")
Yes. As per JacksonAnnotationSerializeNulls, you can use:
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
// or (for older versions):
objectMapper.configure(SerializationConfig.WRITE_NULL_PROPERTIES, false);
and voila, no more null values. Note that you MUST configure mapper before beans are serialized, since this setting may be cached along with serializers. So setting it too late might prevent change from taking effect.
my issue was bit different actually i was getting Null values for the properties of POJO class.
however i solved the problem by giving mapping to properties in my pojo class like this :
#JsonProperty("PROPERTY_NAME")
thought it may help someone :)
The following solution saved me.
objectMapper.setSerializationInclusion(Include.NON_NULL);