my JSON is :
{
"errorMessages" : [ {
"key" : "QUIESCE_FAILURE",
"code" : "12345",
"description" : "User already exists aaa",
"reason" : "Username {user} is already added aaa",
"resolution" : "Please provide a different username aaa",
"more_information" : "more info aaa",
"type" : "error aaa"
}, {
"key" : "DUPLICATE_USERS",
"code" : "3114587",
"description" : "Failed to quiesce database(s)",
"reason" : "Database {database} on host {host} is not accessible",
"resolution" : "Please check that the database is accessible",
"more_information" : "kkkk",
"type" : "error"
} ]
}
i want to delete json with code 3114587 using jackson.
may i get any suggestion?
Thanks in advance.
I suppose you have your JSON contents as a File object.
If you have it as an URL, InputStream, Reader or String,
then just modify the code below by taking another readValue method.
With the classes from packages com.fasterxml.jackson.databind
and com.fasterxml.jackson.databind.node
you can achieve your goal in a straight-forward way.
Read the JSON input, find and remove the array element, and write the JSON output:
File file = ...;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT); // for pretty print
JsonNode jsonNode = objectMapper.readValue(file, JsonNode.class);
ArrayNode errorMessages = (ArrayNode) jsonNode.get("errorMessages");
for (int i = 0; i < errorMessages.size(); i++) {
ObjectNode errorMessage = (ObjectNode) errorMessages.get(i);
String code = errorMessage.get("code").asText();
if (code.equals("3114587")) {
errorMessages.remove(i); // remove the element
}
}
objectMapper.writeValue(System.out, jsonNode);
delete json[key];
Store your Json object in a variable name json. Find the key that you want to delete and it should work.
Related
Assuming that I have this JSON:
{
"response" : {
"code" : "XXX",
"label" : "Lorem Ipsum",
"items" : [
{
"code" : "200",
"label" : "200 !!!"
},
{
"code" : "300",
"label" : "300 !!!!!"
},
{
"code" : "500",
"label" : "+500 !!!!!"
}]
}
}
I want to get the label of the item when code = 500 (as for example) in Java.
I'm using jayWay Library and this jsonPath:
"$.response.items[?(#.code='500')].label"
I'm getting this error while parsing : Expected character: )
The java code :
public static String getElementValueByJsonPath(String jsonContent, String jsonPath) {
if (checkJsonValidity(jsonContent)) {
String returnedValue ="";
Configuration config = Configuration.defaultConfiguration().addOptions(Option.SUPPRESS_EXCEPTIONS);
try {
returnedValue = ""+JsonPath.using(config).parse(jsonContent).read(jsonPath);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return returnedValue;
}
return null;
Anyone knows why I have this error, and can I bypass it with another library or method.
Thanks
You get the error for a very valid reason, that is not a valid jsonpath query.
If you go to https://jsonpath.herokuapp.com/ ( which uses jayway ) and enter the same data and path you will see this is not a valid jsonpath query for jayway, or two of the other implementations, the only one that does not fail outright does not return what you are expecting. I think you need to go back and re-read the jsonpath documentation as this syntax clearly is not valid.
The correct syntax is $.response.items[?(#.code=='500')].label as the documentation clearly states.
I would not rely on implementations that do not fail on incorrect syntax.
So I have a JSON object that looks like this:
{
"accessToken" : "<dont need this>",
"clientToken" : "<nor this>",
"selectedProfile" : {
"id" : "<nope>",
"name" : "<I need this>",
"legacy" : true
},
"availableProfiles" :
[
{
"id" : "<not this>",
"name" : "<not this>",
"legacy" : true
}
]
}
So what I need is selectedProfile > name. I am able to extract selected profiles, would I just repeat the process on that? What should I do to retrieve it?
Using javax.json
JsonReader reader = new JsonReader(yourString);
JsonObject base = reader.readObject();
JsonObject profile = base.getJsonObject("selectedProfile");
String name = profile.getJsonString("name");
and then name should be the object you want.
Try this:
String name = yourJSON.getJSONObject("selectedProfile").getString("name").toString();
I want to parse the JSON objects from my log file. For using JSON Parser my complete files has to be in JSON format which is not the case with me. Is there any way I can parse the file line by line and get the JSON objects.
Below is my log file format:
2015-10-19 11:24:35:701 INFO BrokerTcpClient:28 - Set destination
2015-10-19 11:24:35:929 DEBUG BrokerTcpClient:32 - received data: {type=data, payload={
"core" : [ {
"id" : {
"datatype" : "http://www.w3.org/2001/hk#long",
"type" : "gh",
"value" : "gh"
},
"entity" : {
"type" : "uri",
"value" : "http://fg.fg.com/ext/g/fg"
},
"Sno" : {
"type" : "literal",
"value" : "fg"
}]
2015-10-19 11:24:35:701 INFO BrokerTcpClient:28 - Set destination
2015-10-19 11:24:35:929 DEBUG BrokerTcpClient:32
"core" : [ {
"id" : {
"datatype" : "http://www.w3.org/2001/hk#long",
"type" : "gh",
"value" : "gh"
},
"entity" : {
"type" : "uri",
"value" : "http://fg.fg.com/ext/g/fg"
},
"Sno" : {
"type" : "literal",
"value" : "fg"
}]
Can any one please help how should I get my JSON objects. When I am trying to parse a single line of JSON objects throwing an exception.
Here is a solution that works for the sample log that is posted.
import java.io.*;
import com.fasterxml.jackson.databind.*;
public class JSONTest {
public static void main(String[] args) {
String logFilename = "C://Temp/sample.log";
String line, json = "";
try (BufferedReader br = new BufferedReader(new FileReader(logFilename))) {
while ((line = br.readLine()) != null) {
if (isLogLine(line)) {
if (!json.isEmpty()) {
parseJson(json);
json = "";
}
} else {
json += line;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean isLogLine(String line) {
return line.matches("^\\d{4}\\-\\d{2}\\-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}:\\d{3}.+$");
}
public static void parseJson(String json) throws Exception {
if (!json.startsWith("{") && !json.endsWith("}")) json = "{" + json + "}";
ObjectMapper om = new ObjectMapper();
System.out.println(om.readValue(fixJson(json), Object.class));
}
public static String fixJson(String json) {
return "{" + json.replace("}]", "}}]") + "}";
}
}
Notes:
the regex that identifies log line is checking for timestamp at the
begining of the line. this will not work in case the log message
spans multiple lines (for example if the message contains new line)
there is a method that attempts to "fix" the incomplete json from the log file, it may need additional logic, if there are more cases of incomplete json along the way
I used Jackson Json parser and let ObjectMapper figure out what data structure to parse into
Have you looked into logstash (https://www.elastic.co/products/logstash)? It can solve this problem and perhaps other problems you will come across when trying to parse logs.
So I came across this tutorial for serializing a POJO to json and then de-serialize the json file back to the POJO. http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
he uses these helpful methods which worked for me but only for a single POJO in the file:
//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);
How can I de-serialize a list of POJOs? My serialized file looks like the below:
[ {
"name" : {
"first" : "Wonder",
"last" : "Woman"
},
"ssn" : "123-456-7890",
"gender" : "FEMALE",
"verified" : false
}, {
"name" : {
"first" : "Bat",
"last" : "Man"
},
"ssn" : "321-456-0987",
"gender" : "FEMALE",
"verified" : true
}, {
"name" : {
"first" : "Super",
"last" : "Man"
},
"ssn" : "321-654-1111",
"gender" : "FEMALE",
"verified" : true
} ]
One option (probably the easiest) is to define a class that contains a list of Users:
public class Users
{
public User[] users;
}
Then performing
ObjectMapper mapper = new ObjectMapper();
Users users = mapper.readValue(new File("c:\\user.json"), Users.class);
Another option would be to iterate over the json array, and capture each element of the array of users, then use ObjectMapper.readValue(String content, Class<T> valueType), like so:
ObjectMapper mapper = new ObjectMapper();
InputStream stream = new FileInputStream("c:\\user.json");
User user;
JsonNode json = mapper.readTree(stream);
//NOTE: calling json.isArray() should return true.
for (JsonNode userJson : json)
{
user = mapper.readValue(userJson, User.class);
// use the constructed user...
}
Note: I haven't tested the above, so let me know if it works or not.
Hmmh? Have you tried:
User[] users = mapper.readValue(new File("c:\\user.json"), User[].class);
In your top level class, you have an array of people. something like this
class People {
public List<Person> persons;
}
I'm using the package org.json to parse a JSONArray (I have the json strings saved in a database). However, I don't succeed in parsing it when the same key could have associated a String or a JSONObject, depending on the context.
For example, see the following JSON code...
[ { "cssClass" : "input_text",
"required" : "undefined",
"values" : "First Name"
},
{ "cssClass" : "checkbox",
"required" : "undefined",
"title" : "What's on your pizza?",
"values" : { "2" : { "baseline" : "undefined",
"value" : "Extra Cheese"
},
"3" : { "baseline" : "undefined",
"value" : "Pepperoni"
}
}
}
]
In the code above, the key "values" has 2 possibilities...
A String with value "First Name"
A JSONObject with value {"2":{"value":"Extra Cheese","baseline":"undefined"},"3":{"value":"Pepperoni","baseline":"undefined"}}.
How am I able to process this correctly when the value could be 2 different data types?
You'll probably still need to detect whether it is a JSONObject or a String, so that you can process it further, but perhaps something here might help...
You could try something like this...
String cssClass = myJson.getString("cssClass");
if (cssClass.equals("input_text")){
// Read it as a String
String values = myJson.getString("values");
}
else if (cssClass.equals("checkbox")){
// Read it as a JSONObject
JSONObject values = myJson.JSONObject("values");
// further processing here
}
Or maybe something like this...
String cssClass = myJson.getString("cssClass");
String values = myJson.getString("values");
if (cssClass.equals("input_text")){
// do nothing - it's already a String
}
else if (cssClass.equals("checkbox")){
// Parse the String into a JSONObject
JSONObject valuesObject = new JSONObject(values);
// further processing here
}
Think it this way in js or java duplicate variable creation under same scope is invalid,so to avoid ambiguity put them in separate json object with different variable names before putting it to the json array.