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 ]
Related
I want to update request fields only in an array using java.This is my existing document in mongo db:
{
"_id": "6691e5068dwe335w42cb0a699650f",
"Opportunity_Owner": "Self",
"Account_Name": "IC",
"Lead_Source": "Callbox",
"Opportunity_Name": "name1 ",
"Stage": "Proposal",
"Stage_Status": "A",
"1555570551211": [],
"1555556165153": [],
"1555556059584": [{
"id": "1557389940585",
"Notes": "Note 1"
},
{
"id": "1557389945398",
"Notes": "Hi Bobby "
},
{
"id": "1557389978181",
"Notes": "Spoken to Bobby."
},
{
"id": "1557389990159",
"Notes": "plan to call on 29/Apr"
}
],
"createdBy": "2c18b8dbb7d74a41a66f53a90117480a",
"createdDate": "1562911250917"
}
Request payload:
{
"_id" : "6691e5068dwe335w42cb0a699650f",
"Stage_Status" : "I",
"1555556059584" : [
{
"id" : "1557389940585",
"Notes" : "updated note 123"
}
]
}
I am trying to update "Stage_Status" and "1555556059584.Notes" at a time using $set.I am able to update "Stage_Status" but "1555556059584" array is going to reset with what i have updated with last one.
expected output:
{
"_id" : "6691e5068dwe335w42cb0a699650f",
"Opportunity_Owner" : "Self",
"Account_Name" : "IC",
"Lead_Source" : "Callbox",
"Opportunity_Name" : "name1 ",
"Stage" : "Proposal",
"Stage_Status" : "I",
"1555570551211" : [],
"1555556165153" : [],
"1555556059584" : [
{
"id" : "1557389940585",
"Notes" : "updated note 123"
},
{
"id" : "1557389945398",
"Notes" : "Hi Bobby "
},
{
"id" : "1557389978181",
"Notes" : "Spoken to Bobby."
},
{
"id" : "1557389990159",
"Notes" : "plan to call on 29/Apr"
}
],
"createdBy" : "2c18b8dbb7d74a41a66f53a90117480a",
"createdDate" : "1562911250917"
}
can any one please help me to figure it out in java.
I guess you wanted to update Stage_Status and 1555556059584.Notes at Once .
here is a demo about it
> db.student.find()
{ "_id" : ObjectId("5d2c09ea8ed60ae70d3dd76b"), "name" : "bigbang", "courses" : [ { "name" : "en", "classRoom" : "9001" }, { "name" : "math", "classRoom" : "1001" } ] }
> db.student.update({name:'bigbang','courses.name':'en'},{ $set: {'courses.$.classRoom':'1009',name :"course"} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : ObjectId("5d2c09ea8ed60ae70d3dd76b"), "name" : "course", "courses" : [ { "name" : "en", "classRoom" : "1009" }, { "name" : "math", "classRoom" : "1001" } ] }
the java demo is like this
collection.updateOne(and(eq("Stage_Status","A"),eq("1555556059584.id","1557389940585")),new Document("$set" ,new Document("Stage_Status","YOUR_NEW_VALUE").append("1555556059584.$.Notes","YOUR_NEW_VALUE")));
you must set the 1555556059584.id to let the diver know which element to be update .
hello all i have a collection like this ` "_id" : ObjectId("55dabba974cd60712be24443"),
"entityType" : "1",
"entityCreatedDate" : "08/24/2015 12:07:20 PM",
"nameIdentity" : [
{
"givenNameOne" : "JOY",
"givenNameThree" : "BRAKEL",
"lastName" : "BRAKEL",
"createdDate" : "08/24/2015 12:07:20 PM",
"sourceId" : [
{
"sourceId" : "55dabba974cd60712be24441"
}
]
},
],
Here name identity is a list as well as sourceId. I am trying to update sourceId list in nameIdentityList if it matches the names. My java code is :
Document sourceDocument=new Document("sourceId",sourceId);
mongoDatabase.getCollection("entity").updateOne(new Document("entityId", entityId).append("nameIdentity.givenNameOne","JOY"),
new Document("$push", new Document("nameIdentity.sourceId", sourceDocument)));
` But i am getting exception like java.lang.RuntimeException: com.mongodb.MongoWriteException: cannot use the part (nameIdentity of nameIdentity.sourceId) to traverse the element ({nameIdentity.
If my condition is satisfied i am expecting like this:
`"_id" : ObjectId("55dabba974cd60712be24443"),
"entityType" : "1",
"entityCreatedDate" : "08/24/2015 12:07:20 PM",
"nameIdentity" : [
{
"givenNameOne" : "JOY",
"givenNameThree" : "BRAKEL",
"lastName" : "BRAKEL",
"createdDate" : "08/24/2015 12:07:20 PM",
"sourceId" : [
{
"sourceId" : "55dabba974cd60712be24441"
},
{
"sourceId" : "55dabba974cd60712be24435"
}
]
},
],`
. any suggestions where am i going wrong?
I have multiple names in my nameIdentity, even if the matched document is second or third , sourceId is always being appened to first document. How do i update to specific matched document.
You missed the positional $ operator after the "nameIdentity" field in $push:
Document sourceDocument=new Document("sourceId",sourceId);
mongoDatabase.getCollection("entity").updateOne(
new Document("entityId", entityId).append("nameIdentity.givenNameOne","JOY"),
new Document("$push", new Document("nameIdentity.$.sourceId", sourceDocument))
);
The $push action like other update action modifiers needs to know the "index" of the matched array element to work on. Otherwise the error as you reported occurs.
Ok so I am making API requests to retrieve certain things like movies, songs, or to ping the server. However all of these responses are contained within the same response JSON object that has varying fields depending on the response. Below are three examples.
ping
{
"response" : {
"status" : "ok",
"version" : "0.9.1"
}
}
getIndexes
{
"response" : {
"status" : "ok",
"version" : "0.9.1",
"indexes" : {
"index" : [ {
"name" : "A",
"movie" : [ {
"id" : "150",
"name" : "A Movie"
}, {
"id" : "2400",
"name" : "Another Movie"
} ]
}, {
"name" : "S",
"movie" : [ {
"id" : "439",
"name" : "Some Movie"
}, {
"id" : "209",
"name" : "Some Movie Part 2"
} ]
} ]
}
}
}
getRandomSongs
{
"response" : {
"status" : "ok"
"version" : "0.9.1"
"randomSongs" : {
"song": [ {
"id" : "72",
"parent" : "58",
"isDir" : false,
"title" : "Letter From Yokosuka",
"album" : "Metaphorical Music",
"artist" : "Nujabes",
"track" : 7,
"year" : 2003,
"genre" : "Hip-Hop",
"coverArt" : "58",
"size" : 20407325,
"contentType" : "audio/flac",
"suffix" : "flac",
"transcodedContentType" : "audio/mpeg",
"transcodedSuffix" : "mp3",
"duration" : 190,
"bitRate" : 858,
"path" : "Nujabes/Metaphorical Music/07 - Letter From Yokosuka.flac",
"isVideo" : false,
"created" : "2015-06-06T01:18:05.000Z",
"albumId" : "2",
"artistId" : "0",
"type" : "music"
}, {
"id" : "3135",
"parent" : "3109",
"isDir" : false,
"title" : "Forty One Mosquitoes Flying In Formation",
"album" : "Tame Impala",
"artist" : "Tame Impala",
"track" : 4,
"year" : 2008,
"genre" : "Rock",
"coverArt" : "3109",
"size" : 10359844,
"contentType" : "audio/mpeg",
"suffix" : "mp3",
"duration" : 258,
"bitRate" : 320,
"path" : "Tame Impala/Tame Impala/04 - Forty One Mosquitoes Flying In Formation.mp3",
"isVideo" : false,
"created" : "2015-06-29T21:50:16.000Z",
"albumId" : "101",
"artistId" : "30",
"type" : "music"
} ]
}
}
}
So basically my question is, how should I structure my model classes to use for parsing these responses? At the moment I have an abstract response object that only contains fields for the status and version. However, by using this approach I will need a response class that extends this abstract class for ever request I make (e.g. AbstractResponse, IndexesResponse, RandomSongsResponse). Also, some models with the same name may have different fields depending on the API request made. I would prefer to avoid making a model class for every possible scenario.
And as an extra note, I am using GSON for JSON serialization/deserialization and Retrofit to communicate with the API.
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
How can I navigate JSON string from one key to another nested key and get the value? I have the following string
{ "data" : { "current_condition" : [ { "cloudcover" : "75",
"humidity" : "29",
"observation_time" : "07:59 PM",
"precipMM" : "0.0",
"pressure" : "1011",
"temp_C" : "19",
"temp_F" : "67",
"visibility" : "16",
"weatherCode" : "116",
"weatherDesc" : [ { "value" : "Partly Cloudy" } ],
"weatherIconUrl" : [ { "value" : "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png" } ],
"winddir16Point" : "N",
"winddirDegree" : "350",
"windspeedKmph" : "26",
"windspeedMiles" : "16"
} ],
"request" : [ { "query" : "01801",
"type" : "Zipcode"
} ],
"weather" : [ { "date" : "2011-05-09",
"precipMM" : "0.0",
"tempMaxC" : "19",
"tempMaxF" : "65",
"tempMinC" : "10",
"tempMinF" : "50",
"weatherCode" : "113",
"weatherDesc" : [ { "value" : "Sunny" } ],
"weatherIconUrl" : [ { "value" : "http://www/images/wsymbols01_png_64/wsymbol_0001_sunny.png" } ],
"winddir16Point" : "NNW",
"winddirDegree" : "348",
"winddirection" : "NNW",
"windspeedKmph" : "24",
"windspeedMiles" : "15"
},
{ "date" : "2011-05-10",
"precipMM" : "0.1",
"tempMaxC" : "13",
"tempMaxF" : "56",
"tempMinC" : "12",
"tempMinF" : "53",
"weatherCode" : "122",
"weatherDesc" : [ { "value" : "Overcast" } ],
"weatherIconUrl" : [ { "value" : "http://www/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png" } ],
"winddir16Point" : "NNE",
"winddirDegree" : "12",
"winddirection" : "NNE",
"windspeedKmph" : "31",
"windspeedMiles" : "19"
}
]
} }
So I answer my own question:
In case someone else want to get value quickly: This is what I was looking for.
JSONObject j = new JSONObject(strResponse);
String weatherDesc = jObject.getJSONObject("data").getJSONArray("weather").getJSONObject(0).getJSONArray("weatherDesc").getJSONObject(0).getString("value");
There are JSON libraries in pretty much any language. If you suggest one, I might be able to point you to something.
In the meantime, here are a few:
Perl JSON library
Python's is built in
Javascript serializes its objects in JSON so it's super easy
C# library -- also see C# - parsing json formatted data into nested hashtables
Here's the Android JSON reference
And so on. I suggest a quick google for the language of your choice.
Generally speaking you will use a library that is already built specifically for you language, what language are you trying to read the data in? Many languages have a couple of libraries available, some languages may have built in support, like JavaScript.
if you just need to understand the data, it is pretty readable...