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.
Related
I have an String called inputJson that contains
{"listPruebas": [
{
"nombrePrueba" : "pruebaA",
"id" : 1,
"tipoPrueba" : "PRUEBABASE1",
"elementoBase" : "tipoA",
"listaMarca": [
{
"elemento": "elemento1 ",
"tipo": "ABC",
"cadena": "SFSG34235WF32"
},
{
"elemento":"elemento2",
"tipo":"DEF",
"cadena":"DJRT64353GSDG"
},
{
"elemento" : "elemento3",
"formato ":"JPG"
}
]},
{
"nombrePrueba" : "pruebaB",
"id" : 2,
"tipoPrueba" : "PRUEBABASE2",
"elementoBase" : "imagenPrueba",
"listaMarca2": [
{
"elemento" : "imagen",
"tipo": "tipo5",
"cadena": "iVBORw0KGgoAAAANSUhEUgAAAgAAAA"
}
]
}
],
"listaBuscar":
[
{
"tipoBusqueda":"busqueda1",
"id" : 1,
"operacion" : "operacion1",
"valor" : "12"
},
{
"tipoBusqueda":"binario",
"id" : 2,
"operacion" : "operacion2",
"valor" : "13"
},
{
"tipoFiltro":"numerico",
"id" : 31,
"operacion" : "MENOR_QUE",
"valor" : "1980",
"intervalo" : 1
}
]
}
and I converted the String to JSONObject of this way
JSONObject object = new JSONObject(inputJson);
and I got this
jsonObject::{"listaBuscar":[{"valor":"12","id":1,"operacion":"operacion1","tipoBusqueda":"busqueda1"},{"valor":"13","id":2,"operacion":"operacion2","tipoBusqueda":"binario"},{"tipoFiltro":"numerico","intervalo":1,"valor":"1980","id":31,"operacion":"MENOR_QUE"}],"listPruebas":[{"listaMarca":[{"tipo":"ABC","elemento":"elemento1","cadena":"SFSG34235WF32"},{"tipo":"DEF","elemento":"elemento2","cadena":"DJRT64353GSDG"},{"elemento":"elemento3","formato":"JPG"}],"elementoBase":"tipoA","tipoPrueba":"PRUEBABASE1","nombrePrueba":"pruebaA","id":1},{"elementoBase":"imagenPrueba","tipoPrueba":"PRUEBABASE2","listaMarca2":[{"tipo":"tipo5","elemento":"imagen","cadena":"iVBORw0KGgoAAAANSUhEUgAAAgAAAA"}],"nombrePrueba":"pruebaB","id":2}]}
and now I need to extract information but I dont know how to do, for example I try this
object.getString("elemento1");
but I got this error
Caused by: org.json.JONException: JSONObject["elemento1"] not found
help me please
You can't get a nest JSON object from the top level. It's like a treemap. You need to convert it into a java object or get it level by level.
check this post, a lot of ways.
You json contains two json arrays, fetch them as -
JSONArray listaBuscArray = jsonObj.getJSONArray("listaBuscar");
JSONArray listPruebasArray = jsonObj.getJSONArray("listPruebas");
Now you can process and use them as -
for(int i=0; i<listaBuscArray.length; i++){
JSONObject obj = listaBuscArray.getJSONObject(i);
.... your logic
}
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'm getting an JSON array as a string value and I need to create a JSON object using that. array code is like this.
{"eventsList" : [
"requestId" : "82334-adf86d-8bac8ef-289c"
events:[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
i try to create an JSON object using folowing code line
SONObject jsonObject = new JSONObject(string);
I'm getting an error when i run this.
org.json.JSONException: Expected a ',' or ']' at character 35
at org.json.JSONTokener.syntaxError(JSONTokener.java:413)
at org.json.JSONArray.<init>(JSONArray.java:143)
at org.json.JSONTokener.nextValue(JSONTokener.java:351)
at org.json.JSONObject.<init>(JSONObject.java:206)
at org.json.JSONObject.<init>(JSONObject.java:420)
Please help me to solve this issue.
There are several mistakes.
After [ a list of comma-separated values is expected, but you have a colon after "requestId". You probably meant for the [ on line 1 to be a {.
Given the last issue, you probably want a comma after "82334-adf86d-8bac8ef-289c"
If you drop your text into an online JSON formatter and validator, such as this one it will point out all your errors.
Problem is here:
...
"requestId" : "82334-adf86d-8bac8ef-289c"
events:...
You forgot some punctuation:
...
"requestId" : "82334-adf86d-8bac8ef-289c",
"events":......
Use this instead this is JSON syntax. All keys are strings.
This is how the String should be;
{"eventsList" : [
{"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
the requestId and event must be like this: {"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":
And also there must be closing } after closing the inner JSONArray ]
I have the following gridfs in a mongodb database:
db.outputFs.files.find()
{ "_id" : ObjectId("000000000000000000000001"), "chunkSize" : 261120, "length" : 232, "md5" : "42290309186cc5420acff293b92ae21d", "filename" : "/tmp/outputFs-01.tmp", "contentType" : null, "uploadDate" : ISODate("2015-04-13T13:50:48.259Z"), "aliases" : null, "metadata" : { "estado" : "FICHERO_PDTE_ENVIO", "dataDate" : "20141122", "inputOutputFs" : "output", "gridFileCompression" : "bzip2", "fileType" : "OUTPUT-TEST1", "filePath" : "/tmp/outputFs-01.tmp", "sourceParticipant" : "0100", "destinationParticipant" : "REE", "exportFileName" : "F1_0100_20141122_20150219.0", "processed" : "false", "fileMD5" : "4276e61a4b63d3d1d1b77e27e792bd13", "version" : 0 } }
{ "_id" : ObjectId("000000000000000000000002"), "chunkSize" : 261120, "length" : 232, "md5" : "42290309186cc5420acff293b92ae21d", "filename" : "/tmp/outputFs-02.tmp", "contentType" : null, "uploadDate" : ISODate("2015-04-13T13:50:48.259Z"), "aliases" : null, "metadata" : { "estado" : "FICHERO_ENVIADO_OK", "fechaEnvio" : ISODate("2015-04-13T13:50:48.259Z"), "dataDate" : "20141123", "inputOutputFs" : "output", "gridFileCompression" : "bzip2", "fileType" : "OUTPUT-TEST2", "filePath" : "/tmp/outputFs-02.tmp", "sourceParticipant" : "0100", "destinationParticipant" : "REE", "exportFileName" : "F1_0100_20141123_20150220.0", "processed" : "false", "fileMD5" : "4276e61a4b63d3d1d1b77e27e792bd13", "version" : 0 } }
db.outputFs.chunks.find()
{ "_id" : ObjectId("000000000000000000000001"), "files_id" : ObjectId("000000000000000000000001"), "n" : 0, "data" : { "$type" : 0, "$binary" : "QlpoOTFBWSZTWZSBQ/YABX5cAAAYQAH/+CAAMAFWA0NqptIb9UgAZ6qowAAFKSaJpGhk8ssmVlk7AAAALZtZZOf0vr859OqflcIs461Dm1skcSOpGpHMuu5HcsJG0j5I9PiR4kaRvvjWskfsVMkZVLxI3uRy/pGTqRj7VmMyTOBfUtb561rwkf0j09+Zbkd+cs1I77861xI7pypvfOt1v5DmR1I51nW7XGdaluRnGZjMzJMzOZGpHnrfGM56+/fnGPVVVVVqqpVVWxCSxCTSAEMkZI3IyqXuqXyRuR/i7kinChISkCh+wA==" } }
{ "_id" : ObjectId("000000000000000000000002"), "files_id" : ObjectId("000000000000000000000002"), "n" : 0, "data" : { "$type" : 0, "$binary" : "QlpoOTFBWSZTWZSBQ/YABX5cAAAYQAH/+CAAMAFWA0NqptIb9UgAZ6qowAAFKSaJpGhk8ssmVlk7AAAALZtZZOf0vr859OqflcIs461Dm1skcSOpGpHMuu5HcsJG0j5I9PiR4kaRvvjWskfsVMkZVLxI3uRy/pGTqRj7VmMyTOBfUtb561rwkf0j09+Zbkd+cs1I77861xI7pypvfOt1v5DmR1I51nW7XGdaluRnGZjMzJMzOZGpHnrfGM56+/fnGPVVVVVqqpVVWxCSxCTSAEMkZI3IyqXuqXyRuR/i7kinChISkCh+wA==" } }
When I try to retrieve it with Spring Data or even MongoChef (both Java clients) as a file, I receive the following error:
com.mongodb.BasicDBObject cannot be cast to [B
The collections were manually imported as they are, not using MongoChef or mongofiles and I have no idea where this error can come from.
The GridFS specification expects a Binary field called data in the chunks collection. However, your outputFs.chunks does not meet this criteria.
The data field here is not a Binary BSON data type but a regular document that happens to have two fields called $type and $data.
mongoimport will create a Binary field only for JSON entries in the following format. Please note that the order of the fields matters for mongoimport.
{
"$binary" : ...
"$type" : ...
}
Your example has the $type and $binary fields swapped.
Update your JSON file and import your outputFs.chunks again. mongoimport will create valid Binary fields and you'll be able to work with GridFS using your other MongoDB tools.
I want to get a specific element of the array and through the responsaveis.$ (daniela.morais#sofist.com.br) but there is no result, there is problem in my syntax?
{
"_id" : ObjectId("54fa059ce4b01b3e086c83e9"),
"agencia" : "Abc",
"instancia" : "dentsuaegis",
"cliente" : "Samsung",
"nomeCampanha" : "Serie A",
"ativa" : true,
"responsaveis" : [
"daniela.morais#sofist.com.br",
"abc#sofist.com.br"
],
"email" : "daniela.morais#sofist.com.br"
}
Syntax 1
mongoCollection.findAndModify("{'responsaveis.$' : #}", oldUser.get("email"))
.with("{$set : {'responsaveis.$' : # }}", newUser.get("email"))
.returnNew().as(BasicDBObject.class);
Syntax 2
db.getCollection('validatag_campanhas').find({"responsaveis.$" : "daniela.morais#sofist.com.br"})
Result
Fetched 0 record(s) in 1ms
The $ positional operator is only used in update(...) or project calls, you can't use it to return the position within an array.
The correct syntax would be :-
Syntax 1
mongoCollection.findAndModify("{'responsaveis' : #}", oldUser.get("email"))
.with("{$set : {'responsaveis.$' : # }}", newUser.get("email"))
.returnNew().as(BasicDBObject.class);
Syntax 2
db.getCollection('validatag_campanhas').find({"responsaveis" : "daniela.morais#sofist.com.br"})
If you just want to project the specific element, you can use the positional operator $ in projection as
{"responsaveis.$":1}
db.getCollection('validatag_campanhas').find({"responsaveis" : "daniela.morais#sofist.com.br"},{"responsaveis.$":1})
Try with this
db.validatag_campanhas.aggregate(
{ $unwind : "$responsaveis" },
{
$match : {
"responsaveis": "daniela.morais#sofist.com.br"
}
},
{ $project : { responsaveis: 1, _id:0 }}
);
That would give you all documents which meets that conditions
{
"result" : [
{
"responsaveis" : "daniela.morais#sofist.com.br"
}
],
"ok" : 1
}
If you want one document that has in its responsaveis array the element "daniela.morais#sofist.com.br" you can eliminate the project operator like
db.validatag_campanhas.aggregate(
{ $unwind : "$responsaveis" },
{
$match : {
"responsaveis": "daniela.morais#sofist.com.br"
}
}
);
And that will give you
{
"result" : [
{
"_id" : ObjectId("54fa059ce4b01b3e086c83e9"),
"agencia" : "Abc",
"instancia" : "dentsuaegis",
"cliente" : "Samsung",
"nomeCampanha" : "Serie A",
"ativa" : true,
"responsaveis" : "daniela.morais#sofist.com.br",
"email" : "daniela.morais#sofist.com.br"
}
],
"ok" : 1
}
Hope it helps