How to convert JSON string to JSON by using JSONSerializer if the JSON string contains 'class' key? By using toJSON method all 'class' keys are ignored:
String str = "{'test': 'ok', 'class' : 'fail'}";
JSON json = JSONSerializer.toJSON(str) // result is: {"test":"ok"}
I found it:
JsonConfig cfg = new JsonConfig();
cfg.setIgnoreDefaultExcludes(true);
JSON json = JSONSerializer.toJSON(str, cfg) // {"test":"ok", "class":"fail"}
Related
When I serialize String element with \" inside, result is "{\"role\":\"student\", \"userType\":\"techer\"}" How to change result to "{"role":"student", "userType":"techer"}"? Used java, jackson lib.
String value = "{\"role\":\"student\", \"userType\":\"techer\"}";
System.out.println(value); //{"role":"student", "userType":"techer"}
String json2 = new ObjectMapper().writeValueAsString(value);
System.out.println(json2);// "{\"role\":\"student\", \"userType\":\"techer\"}"
I have an object something like this in my database and now my requirement is to find the value of particular field such as name and if present return true,
{
"_id" : "123",
"name" : "Team"
}
but in some case the field name itself doesn't exist. Sample can be something like this:
{
"id":1234
}
In this case I need to return false.
How can I validate if name field exist in particular object?
I was trying to use StringUtils method something like this
StringUtils.isBlank(obj.getName); But its throwing It is throwing java.lang.NullPointerException .
You can use Json schema validator. If your json will be in specific format. Please have a look at Jackson library.
JSONObject class has a method named "has". try this way,
if (json.has("name")) {
String status = json.getString("name"));
}
This will work
You can use Gson Java library to serialize and deserialize Java objects to JSON (as given below).
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(object, JsonObject.class);
Then, you can use the has method in JsonObject, to check if the key exists in it.
jsonObject.has(key)
Example:
Below is a method to check if given key exists in given json string, and get it's value.
(Instead of String, you can use your object as well. Here, I am considering the jsonStr as a String object, for better understanding.)
private String getValueFromJsonForGivenKey(String key, String jsonStr) {
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonStr, JsonObject.class);
if (jsonObject.has(key)) {
// The given JSON string has the given key
String value = jsonObject.get(key).getAsString();
return value;
}
return null;
}
For key id and for jsonStr { "id": "1234" }, we get 1234.
For key name and for jsonStr { "id": "1234" }, we get null.
What you can do is to use JSONObject's opt method
eg.
JSONObject jsonObject = new JSONObject(myJSONString);
String name = jsonObject.optString("name");
Is there a way to convert the whole JSON path data to a string in Java?
I am working on APIs and their responses are in JSON format. It is easy to understand the JSON structure through Postman/WireShark but I am trying to run an API request through Java, grab the response, convert the raw response to JSON, convert JSON response to a string format and print it. The method '.getString()' is to access a particular element and not the whole data. The method '.toString()' does not work on JSON data either.
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String id = json.get("id");
log.info("The id is " + id);
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = ???;
log.info("The complete json data is " + complete_json_data);
The code snippet which is mentioned "???" is what I was trying to achieve.
The methods which can convert a JsonPath object into a String are:
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = json.prettify();
and
JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = json.prettyPrint();
var obj = { "field1":"foo", "age":55, "city":"Honolulu"};
var myJSON = JSON.stringify(obj);
Here is my json:
{
"timestamp":"04295d4f-2a6f-4a38-a818-52108cbdc358",
"lastFullSyncDate":null,
"ftpInfo":null,
"listingInfo":{
"itemID":"110179365615",
"itemTitle":"test",
"itemPrice":"88.2235294117647",
.......
....
.....
}
}
I have a java class named listingInfo was trying to use gson to convert the string with the key of listingInfo to the class, but i'm getting nulls for all the vars.
Gson gson = new Gson();
gson.fromJson(json, ListingInfo.class);
While trying to convert to the part class which contains the time stamp and etc i dot get the vars but the listingInfo is null inside
Is it possible to get into the nested key and only convert him to the class?
You can do it by parsing whole json tree and then extracting the nested key
String json = ...; //your json string
Gson gson = new Gson();
JsonElement element = new JsonParser().parse(json); //parse to json tree
JsonElement listingElement = element.getAsJsonObject().get("listingInfo"); // extract key
ListingInfo listingInfo = gson.fromJson(listingElement, ListingInfo.class);
I have json serialized arraylist in java which i want to insert into another json object, how can i do this without having double quotes on my json string?
JSONSerializer serializer = new JSONSerializer();
String serializedList = serializer.serialize(myArrayList);
I want serializedList nested into my json object:
myJsonOutput = Json.createObjectBuilder()
.add("key1", "val1")
.add("key2", "val2")
.add("myArray", serializedList)
.build();
If i do it like this my serializedList will be inserted as a whole string?