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);
Related
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.
This question already has an answer here:
json object convert to string java
(1 answer)
Closed 2 years ago.
Hi Guys I'm new to programming.
In my java code i have string like this.
String json ="{"name":"yashav"}";
Please help me out to print the values using pre-build java functions.
Expected output should be like below
name=yashav
First of all its not JSON.
If you want to work for actual JSON. There are many libraries which help you to transfer string to object.
GSON is one of those libraries. Use this to covert object then you can use keys to get values. Or you can iterate whole HashMap as per your requirements.
https://github.com/google/gson
{name:yashav} this is not a valid JSON format.
If you have {"name": "yashav"} you can use Jackson to parse JSON to java object.
class Person {
String name;
...
}
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue("{\"name\" : \"mkyong\"}", Person.class);
Forst of all, given String is NOT a json. It should be "{\"name\":\"yashav\"}". If you have a correct json string, you can use JacksonUtils.
Define a model:
class Url {
private String name;
public String getName() {
return name;
}
}
And parse the json string:
String json = "{\"name\":\"yashav\"}";
Url url = JsonUtils.readValue(json, Url.class);
System.out.format("name = %s", url.getName());
Another way is to use Regular Expression:
public static void main(String... args) {
String url = "{name:yashav}";
Pattern pattern = Pattern.compile("\\{(?<key>[^:]+):(?<value>[^\\}]+)\\}");
Matcher matcher = pattern.matcher(url);
if (matcher.matches())
System.out.format("%s = %s\n", matcher.group("key"), matcher.group("value"));
}
And finally, you can use plain old String operations:
public static void main(String... args) {
String url = "{name:yashav}";
int colon = url.indexOf(':');
String key = url.substring(1, colon);
String value = url.substring(colon + 1, url.length() - 1);
System.out.format("%s = %s\n", key, value);
}
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 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)?