Receiving JSON input from server whose parameter name may change with time. output format which also will be a json is fixed. But input json may change as it comes from different publishers. Client want an externaal mapping file(json format also) which they will only modify if input json property name needs to be modified or extra parameter is needed. It's spring boot project. Input Json will be nested and may not be nested depending on the publishers.
Input JSON-1
respective Output JSON-1
Without creating POJO, it is possible. You would need to get json property values by property name. You may like to explore com.google.gson.JsonParser. It takes Json String and parses it.
JsonParser myParser = new JsonParser();
JsonElement elems = myParser.parse(jsonString);
Related
Project: Android app using REST web service
Using:
Client - Volley
Server API - Jersey
Converter: Gson
This is my first time asking a question here, and i will provide my way of "evading" this code convention. Since i am working on a project where POJO fields are already defined as upper-case (sadly, i cant change that), i had to find a way to fix JSON string and convert it to an instance of uppercase POJO.
So basicaly its: client POJO <--> json object converted to/from gson <--> server POJO
So, lets say that i have a field in Users.class
String USERNAME;
When Jersey sends an instance of via #Produces, it follows the convention of creating JSON and sends an object
{"username": "random_name"}
When it gets converted from JSON via gson.fromJSON, an instance of a client's POJO will get null value for that field (obviously because field is in lower-case in JSONObject).
This is how i managed it by using a method that parses JSONObject and puts each key as upper-case:
public static String fixJSONObject(JSONObject obj) {
String jsonString = obj.toString();
for(int i = 0; i<obj.names().length(); i++){
try{
obj.names().getString(i).toUpperCase());
jsonString=jsonString.replace(obj.names().getString(i),
obj.names().getString(i).toUpperCase());
} catch(JSONException e) {
e.printStackTrace();
}
}
return jsonString;
}
And luckily since gson.fromJSON() requires String (not a JSONObject) as a parameter besides Class, i managed to solve the problem this way.
So, my question would be: Is there any elegant way of making JSON ignore that code convention and create a JSON object with an exact field? In this case:
{"USERNAME": "random_name"}
Jersey uses JAXB internally to marshall beans to xml/json. So you can always use #XmlElement annotation and use name attribute to set the attribute name to be used for marshalling
#XmlElement(name="USERNAME")
String USERNAME;
Just use annotation com.google.gson.annotations.SerializedName
Add in class Users.java:
#SerializedName("username")
String USERNAME;
I'm developing a restful web-service that should be able to return JSON or XML responses upon request. Of course, the JSON response should be identical to the XML response when the data is compared.
The thing is that I can't use a Java pojo because the returned data fields are dynamic, they are unpredictable.
For example, a specific user may have the following response:
{
"propertyA": "propertyA-Value",
"propertyB": "propertyB-Value",
}
...another user may have:
{
"propertyA": "propertyA-Value",
"propertyB": "propertyB-Value",
"propertyC": "propertyC-Value",
}
...or the XML representation would be
<results>
<propertyA>propertyA-Value</propertyA>
<propertyB>propertyB-Value</propertyB>
<propertyC>propertyC-Value</propertyC>
</results>
Is there a way to automatically serialize the structure holding the previously mentioned data, to JSON or XML. By "automatically", I mean using an API that would work with whatever fields provided.
I can't use an array\list of feature-name\feature-value structures as the service consumer needs to receive the response as mentioned.
use codehaus fasterxml object mapper. A sample app can be seen from below link
https://github.com/abhishek24509/JsonMapper
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
the above code will help to hold dyamic response. Your pojo can have all possible field. But during mapping it will ignore unknown
I have a JSON string which I am storing it in DB as a string. In front-end, I am rendering this JSON as object.
I am using:
JSON.parse(string);
Uncaught Syntax error: Unexpected Token
String :
{
"id": "295cd59f-4033-438c-9bf4-c571829f134e",
"from": "Shrisha S.<shrisha#s.com>",
"to": [
"Katie Porter <katie.porter#ss.com>"
],
"cc": [
"Jack d<jack.d#dd.com>, Keerthi<keerthi.s#dd.com>"
],
"bcc": [
]
}
Is there any way I can check If JSON is valid or not in JAVA?
One thing to be noted here is that, I don't have a schema defined for JSON which I can map to, i.e. JSON can hold anything.
I am currently trying out with JACKSON but for that I need a pre-defined schema which I don't have. Is there anyway this can be fixed?
You can read it as a JsonNode, no need to map it to a specific Class, its generic:
try{
ObjectMapper objectMapper = ...;
JsonNode jsonNode = objectMapper.readTree(yourJsonString);
} catch(JsonProcessingException e){........}
There are two different parts to the question. First is whether it is valid JSON, and second whether it contains specific set of information.
#pdem already answered first part (you can also read JSON as java.lang.Object to get the same effect).
But for second part, JSON Schema is not usually a good way, as it focuses on JSON aspects but not on more meaningful part of actual data, possible sub-typing and so on, which matter at Java level where all actual data processing occurs.
So usually you would define a POJO (or ideally just use one you use for actual data processing), bind to it (with ObjectMapper.readValue()), and then check whether data is not only technically valid wrt low-level data types, but also that it conforms to additional business constraints.
For latter part you can either write Java code, or use an annotation based framework such as Bean Validation API (JSR-303); see for example:
http://beanvalidation.org/
plus there are many #bean-validation tagged questions here as well related to usage. Some frameworks add explicit support for it; for example the best Java service framework, DropWizard does this. Others like Spring Boot have support as well.
JSON specification forbids it from using newline characters, make sure you are replacing newline characters see
Regex replace all newline characters with comma
make sure you do this before storing it in DB.
public boolean isValidJson(final String json) {
try {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree(json);
return jsonNode instanceof ContainerNode;
} catch (JsonProcessingException jpe) {
return false;
}
}
I have a user entry form with the following fields :
Name
Age
Address
I want to convert its value to JSON and save it in a database. How can I achieve this?
Which library can I use ?
At server side in servlet save all request parameters to corresponding bean and then you can convert using google's gson library for more info check this tutorial
For example:
You need servlet that takes form submission
To work with JSON I recommend eclipse source minimal JSON, I like it
database - plain JDBC, hibernate or JPA ..
Refer the following steps:
In JSP page, at javascript convert the form fields to JSON using JSON.stringify() method.
At server parse the JSON using appropriate JSON parsers like GSON or Jackson.
After parsing you will get desired object.
Perform database operation on the object.
You will probably need GSON jar , Jackson jar.
I am trying to parse JSON data being sent from UI in my Controller using Spring build Jackson support and this is my code
final Map<String, CartDataHelper> entriesToUpdateMap = new ObjectMapper().readValue(entriesToUpdate, new TypeReference<Map<String, CartDataHelper>>()
my JSON string is
{"0":"{\"categoryCode\":\"shoes\",\"productCode\":\"300050253\",\"initialQty\":\"3\",\"leftoverQty\":\"0\",\"newQty\":\"3\"}",
"1":"{\"categoryCode\":\"shoes\",\"productCode\":\"300050254\",\"initialQty\":\"3\",\"leftoverQty\":\"0\",\"newQty\":\"3\"}"}
i checked the JSON format using some online services and it seems valid, while tryin gto parse JSON data i am getting following exception
org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class controllers.util.CartDataHelper] from JSON String; no single-String constructor/factory method
my CartDataHelper class contains simple properties for for productCode, categoryCode etc with a no argument constructor
As comments mentioned, your JSON contains Map<String,String> and NOT Map<String,CartDataHelper>: values are JSON Strings, not JSON Objects.
Ideally you would not try writing out objects as JSON Strings; and if so, things would work.
It seems that on the client side the json is sent as a string instead as an object. That way on the server side you are receiveing a string and not a CartDataHelper as you pretend.
Try sending JSON.parse(stringCartDataHelper). It worked for me with the same issue.