I am having a string like ,
name = " {
"Name" : "MyName"
}"
and having a Model class like ,
#Valid
Class Model {
#JsonProperty("Name")
#Size(min = 1)
#NotNull
private String name;
}
Now I am converting the string to Java Object by following code,
Model name = objectMapper.readValue(name, Model.class);
So the validation(min = 1 and not null) is not happening with this.
How can I validate when I am converting a string to java object?
i will try to help u.
I have an idea and it´s that u divide the process in 2 parts:
First, u take the json and put in on a JSONObject:
import org.json.JSONObject;
...
JSONObject json= new JSONObject(name);
Then, u can call, for example, a function passing a json that validate the values of json an if is correct return a model object:
public Model functionExample(JSONObject json){
try{
if(json.has("Name") && json.getString("Name")!=null){
return new Model(json.getString("Name"));
}
}catch(Exception ex){
return new Model();
}
}
This check if the field "Name" exists and it´s not null.
I don´t know if it is what u want.
I hope it help u.
Related
I want to convert each integer/double value to String present in json request before storing in MongoDB database.
There can be multiple fields like amountValue in the json. I am looking for a generic way which can parse json with any number of such attributes value to string. My request will have around 200 fields.
ex: "amountValue": 200.00, to "amountValue": "200.00",
{
"templateName": "My DC Template 14",
"templateDetails": {
"beneficiaryName": "Snow2",
"dcOpenAmount": {
"amountValue": 200.00,
}
}
}
My mongoDB Document is of the form
#Document
public class TemplateDetails {
#Id
private long templateId;
private String templateName;
private Object templateDetail;
}
Because we are storing document in mongodb as an object(Which can accept any type of json request) we dont have field level control on it.
In my controller, converting the request object to json.
This is how I tried. But its not meeting my expectation. It is still keeping the amount value to its original double form.:
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(templateRequestVO);
System.out.println("ResultingJSONstring = " + json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Output :
ResultingJSONstring = {"id":null,"userId":"FU.ZONKO","txnType":"LCI","accessIndicator":"Public","templateId":null,"templateName":"My DC Template 14","tags":null,"templateDetails":{"applicantDetail":{"applicantName":"Tom","applicantAddress":{"addressLine1":"Infosys, Phase 2","city":"PUNE","state":"MAHARASHTRA","country":"INDIA","zip":"40039"},"accountId":"Account1234","customerId":"JPMORGAN"},"beneficiaryName":"Snow2","dcOpenAmount":{"amountValue":200.0,"currency":"USD"}}}
Is there any way to accomplish the result ? Or anything which can help to store documents in mongodb with attribute type as String ?
You can use Json manipulation avaliable in "org.json.JSONObject" to convert Double value to Stirng .
If your Json structure won't change and will remain as said above , you can do the following.
import org.json.JSONObject;
public static void main(String args[]) {
String j = "{ \"templateName\": \"My DC Template 14\", \"templateDetails\": { \"beneficiaryName\": \"Snow2\", \"dcOpenAmount\": { \"amountValue\": 200.00 } } }";
JSONObject jo = new JSONObject(j);
jo.getJSONObject("templateDetails")
.getJSONObject("dcOpenAmount")
.put("amountValue", String.valueOf(jo.getJSONObject("templateDetails").getJSONObject("dcOpenAmount").getDouble("amountValue")));
System.out.println(jo.toString());
}
Following will be the output
{"templateDetails":{"dcOpenAmount":{"amountValue":"200.0"},"beneficiaryName":"Snow2"},"templateName":"My DC Template 14"}
I don't know for mongodb but for a json string you can replace them with a regex and the function replace like this :
public class Test {
public static void main(String[] args) {
String json = "{\"id\":null,\"userId\":\"FU.ZONKO\",\"txnType\":\"LCI\",\"accessIndicator\":\"Public\",\"templateId\":null,\"templateName\":\"My DC Template 14\",\"tags\":null,\"templateDetails\":{\"applicantDetail\":{\"applicantName\":\"Tom\",\"applicantAddress\":{\"addressLine1\":\"Infosys, Phase 2\",\"city\":\"PUNE\",\"state\":\"MAHARASHTRA\",\"country\":\"INDIA\",\"zip\":\"40039\"},\"accountId\":\"Account1234\",\"customerId\":\"JPMORGAN\"},\"beneficiaryName\":\"Snow2\",\"dcOpenAmount\":{\"amountValue\":200.0,\"currency\":\"USD\"}}}";
System.out.println(replaceNumberByStrings(json));
}
public static String replaceNumberByStrings(String str){
return str.replaceAll("(?<=:)\\d+(\\.\\d+)?(?=(,|}))","\"$0\"");
}
}
It will look for all fields with a numeric value in the json string and add quotes to the value. This way they will be interpreted as strings when the json willl be parsed.
It will not work if the value is in an array though, but in this case it should not be a problem.
I have a data set. It is of the form
{
"name1": 123
"name2": 234
"name3": 345
.
.
.
}
Now, I am using a #RestController to read this through PostMan. I have a class test.java.
I have a function,
public void testController(#RequestBody String request)
I'm running this through a local host with the help of #RequestMapping. I need to save the above data set one by one in an object. The object is as follows.
public class OperatorClass implements Comparable<OperatorClass>{
private String name;
private ArrayList<String> id = new ArrayList<>();
OperatorClass(String name, String id)
{
add_id(id);
add_name(name);
}
I am trying to save this data in the following way, which by the way I have figured out is wrong.
try {
JSONObject array = new JSONObject(request);
Iterator<String> stringIterator1 = array.keys();
stringIterator1.next();
ArrayList<String> arrayList = new ArrayList<>();
OperatorClass oco = new OperatorClass(array.keys().,array.get(array.keys().toString()).toString());
System.out.println(oco.get_Name());
System.out.println(oco.get_Id());
} catch (Exception e) {
e.printStackTrace();
}
I know it is wrong because array.keys() gives all the name1, name2, name3 data. What I want to know is how to get just name 1 for this. And how to get it's following ID, to insert into a particular object.I was trying to save the object into a set of operator class.
Ok. I have got an answer to this problem. We use
String temp = stringIterator1.next();
And instead of
OperatorClass oco = new OperatorClass(array.keys().,array.get(array.keys().toString()).toString());
We use,
OperatorClass oco = new OperatorClass(temp, array.get(temp).toString);
Just remember that using string iterator will probably not display the values in the order of the data set, due to hash mapping.
I have an integer value, say int id whose value i get runtime by getter function.
I want to replace this value of id in place of "VALUE" from .json like as follows
{
"id":"VALUE",
"name": "Name updated",
"description": "description Updated",
"active": false
}
I found following way to replace it if id is String,
String str = "myJson.json";
str.replace("\"VALUE\"", "\"id\"");
How can i use int id in above function with this format "\"id\"" ?
Any other solution are welcome.
EDIT:
String str = "myJson.json";
is wrong way to get json content into String.
You can do it with simple regex replace, e.g.:
public static void main(String[] args) {
String value = "{\"id\":\"VALUE\",\"name\": \"Name updated\",\"description\": \"description Updated\",\"active\": false}";
int id = 5;
value = value.replaceAll("\"VALUE\"", String.valueOf(id));
System.out.println(value);
}
Using org.json library you can assign it to JSON Object and Use the put method:
JSONObject jsonObject= new JSONObject(YOUR_STRING);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
JSONObject id= jsonArray.getJSONObject(0).getJSONObject("id");
person.put("VALUE", id);
regex replace may create some issue by replace someother matching string .
I did in following way.
To replace content of Json file need to convert contents in to String. I did this with help of following function.
public static String loadJson(String jsonFileName) throws IOException {
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(jsonFileName);
return IOUtils.toString(stream);
}
Then declare a String variable,
String editedJson = loadJson(TEST_SET + "myJson.json");
editedJson.replace("VALUE", "" + id);
I have an entity of:
class A {
String errors ;// a json string of some type (type could vary).
Double value;
...
public A(String theErrors, Double theValue) {
errors = theErrors;
value=theValue;
}
}
A a = new A("{tl:[\"err1\"]...}", 10d);
I need to transform a to a json string.
With google gson library I could use:
String str = gson.toJson(a)
But s.a. errors field is a String, it is escaped, and the result is:
// {"errors": "{ tl:["err1"] ...}", "value":10 }
not a
// {"errors": { tl:["err1"]... }, "value":10 }
As for now I try something like:
String str = gson.toJson(a).replace("\"{", "{").replace("}\"}", "}}")
but that is a fragile solution.
Does anyone know, if there is a better way to fix that? Thanks in advance.
PS: the point is that type of underlying errors object is unknown (it depends on the source of errors)
seems I've found a solution:
String getAsJson(A a) {
JsonObject jsonMedia = (JsonObject) g.toJsonTree(a);
jsonMedia.add("errors", g.fromJson(a.getA(), JsonElement.class));
return g.toJson(jsonMedia);
}
I need to blur the user id present in my original json string with another user id. After that I will construct a new json string with everything same but the only difference will be the user id is different.
As an example, if my original json string is like this -
{
"user_id":{"long":1234},
"client_id":{"int":0},
"affinity":[
{
"try":{"long":55793},
"scoring":{"float":0.19}
},
{
"try":{"long":1763},
"scoring":{"float":0.0114}
}
]
}
Then my new json string will be - The only difference is I have a new user id in it and apart from that everything is same.
{
"user_id":{"long":98765},
"client_id":{"int":0},
"affinity": [
{
"try":{"long":55793},
"scoring":{"float":0.19}
},
{
"try":{"long":1763},
"scoring":{"float":0.0114}
}
]
}
The only problem I have is, I won't have json string in the above format only so I cannot use POJO to serialize my json string since my json string will have different formats but user_id field will always be like that in all my json string and it will be long as well. The other fields might be different depending on the json string I have.
I am using Gson to do this. I have got the below method but not sure how can I construct a new json with newUserId in it and everything should be same?
private static String creatNewJson(String originalJsonResponse, long newUserId) {
JsonElement jelement = new JsonParser().parse(originalJsonResponse);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("user_id");
// not sure what I should do here to construct a new json with newUserId
}
Or Gson is not the right way to do this? Should I be usingg regular expressions for this?
How about input.replaceAll("(\"user_id\":\\{\"long\":)\\d+", "$1" + newID)?