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();
Related
I have the following mongoDB object
{
"_id" : ObjectId("5c3f32a4e17c5739bccb9115"),
"name" : "John",
"friends" : [
{
"name" : "Paul"
},
{
"name" : "Lisa"
}
]
}
I need to delete some element from it. In native mongodb query it looks like
db.users.update({}, {$pull: {friends: {name:"Lisa"}}})
But how can I do this via Morhia API?
I resolve this issue by using:
Query<Group> query = getDatastore().createQuery(Group.class);
UpdateOperations<Group> ops = getDatastore().createUpdateOperations(Group.class)
.removeAll("friends", new BasicDBObject("name", "Lisa"));
getDatastore().update(query, ops);
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.
I would like to convert XML to JSON.
Currently, I make this with the lib org.json :
JSONObject jso = XML.toJSONObject(xmlStr);
However, if the XML contains number fields, I would like to have only String fields in the JSONObject.
For example:
The XML file is :
<ID>3</ID>
<NAME>ApplicationName</NAME>
The org.json permits me to have:
{
"ID" : 3,
"Name" : "ApplicationName"
}
The final result has to be :
{
"ID" : "3",
"Name" : "ApplicationName"
}
I resolve mt problem by using the latest version of org.json.
There is a methode to do this :
JSONObject jso = XML.toJSONObject(xmlStr, true);
The boolean is using to keep the string fields.
In my android application,i calling one webservice and it is returning one jsonobject.In device i getting one response like this..
"{ \"Time_Stamp\" : \"10/10/2012 4:26 PM\", \"records\" : [ { \"'Name'\" : \"'LD-00000002'\", \"'Appointment_Date_Time'\" : \"'null'\", \"'Phone'\" : \"'9909955555'\", \"'Home_Country_Address'\" : \"'null'\", \"'Occupation'\" : \"'null'\", \"'SR_Appointment_Status'\" : \"'Open'\", \"'Id'\" : \"'a0OE0000001iLynMAE'\", \"'SR_Appointment_Comment'\" : \"'testing'\", \"'ProductsOfInterest'\" : \"'null'\", \"'ActivityName'\" : \"'Sales'\", \"documentsList\" : [ ] }, { \"'Name'\" : \"'LD-00000002'\", \"'Appointment_Date_Time'\" : \"'null'\", \"'Phone'\" : \"'9909955555'\", \"'Home_Country_Address'\" : \"'null'\", \"'Occupation'\" : \"'null'\", \"'SR_Appointment_Status'\" : \"'Open'\", \"'Id'\" : \"'a0OE0000001iLynMAE'\", \"'SR_Appointment_Comment'\" : \"'testing'\", \"'ProductsOfInterest'\" : \"'null'\", \"'ActivityName'\" : \"'Sales'\", \"documentsList\" : [ { \"numberOfImages\" : 3, \"Name\" : \"new document\", \"Mandatory\" : false, \"FilePath\" : null, \"Category\" : null } ] } ]}"
i trying convert it into an object like this
JSONObject jsonObj=new JSONObject(objMngr.getResponse());
when converting it throwing one exception "java.lang.String cannot be converted to JSONObject"...below is the exact exception that it is throwig ..What is the reason and how can i solve this issue??
{ "Time_Stamp" : "10/10/2012 4:26 PM", "records" : [ { "'Name'" : "'LD-00000002'", "'Appointment_Date_Time'" : "'null'", "'Phone'" : "'9909955555'", "'Home_Country_Address'" : "'null'", "'Occupation'" : "'null'", "'SR_Appointment_Status'" : "'Open'", "'Id'" : "'a0OE0000001iLynMAE'", "'SR_Appointment_Comment'" : "'testing'", "'ProductsOfInterest'" : "'null'", "'ActivityName'" : "'Sales'", "documentsList" : [ ] }, { "'Name'" : "'LD-00000002'", "'Appointment_Date_Time'" : "'null'", "'Phone'" : "'9909955555'", "'Home_Country_Address'" : "'null'", "'Occupation'" : "'null'", "'SR_Appointment_Status'" : "'Open'", "'Id'" : "'a0OE0000001iLynMAE'", "'SR_Appointment_Comment'" : "'testing'", "'ProductsOfInterest'" : "'null'", "'ActivityName'" : "'Sales'", "documentsList" : [ { "numberOfImages" : 3, "Name" : "new document", "Mandatory" : false, "FilePath" : null, "Category" : null } ] } ]} of type java.lang.String cannot be converted to JSONObject
try
JSONObject jsonObj=new JSONObject(objMngr.getResponse().toString().replace("\\", " "));
Your jsonString seems allright. However your response type may not be string. Try it.
The problem is with already escaped inverted commas sent by the server.
First convert your response to a String then try to create a JSONObject
I think, getResponse() is already string but response isn't valid JSON.If response isn't string,you can convert string with toString() method.
It seem there are some hidden characters on your string.
Try this
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
Seems like you have dumped object to JSON string twice on server-side.
object --dumps()--> json string --dumps()-> one string in json
So you should remove the second dumping.
Otherwise you can unescape your string this way How to unescape a Java string literal in Java?.
The first way is better and easier i think.
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.