Apex JSON parsing error - json

I am getting the following error in my code:
System.JSONException null Don't know the type of the Apex object to
deserialize at [line:1, column:1] 11 (System Code)
Class.FactorLab.FactorLabWebservices.RetrieveUsersFromFactorLab: line
60, column 1 Class.FactorLab.PullUsers.execute: line 61, column 1
Here is the code in question:
public static List<FactorLabPullUser> RetrieveUsersFromFactorLab(List<String> ids){
HttpRequest req = getHttpRequest(baseUrl + '/ws/sfdc/people/retrieve', 'POST');
req.setBody(JSON.serialize(ids));
req.setHeader('Content-Type', 'application/json');
if(Test.isRunningTest()){
return null;
}
HttpResponse res = sendRequest(req);
// This is the line with the error
List<FactorLabPullUser> flusers = (List<FactorLabPullUser>)JSON.deserialize(res.getBody(), Type.forname('List<FactorLabPullUser>'));
return flusers;
}
I'm sure that it's receiving valid JSON, but I'm not sure the exact JSON it's receiving when it gets this error. It could simply get an empty array:
[]
It could also get something like this:
[ { "SFDCStatus" : "RETRIEVED",
"address" : "123 Fake St.",
"addressLine1" : "Address1",
"addressLine2" : "Address2",
"city" : "San Francisco",
"companyName" : "Big Cheese, Inc.",
"deleted" : false,
"email" : "james.willard#fake.com",
"firstName" : "James",
"hireDate" : "2000-04-15T00:00:00Z",
"id" : 39,
"lastName" : "Willard",
"lastUpdated" : "2011-11-23T05:44:03Z",
"myersBriggs" : "SFDC",
"name" : "James Willard",
"phone" : "415-555-1212",
"position" : "Big Chief",
"regions" : [ { "deleted" : false,
"id" : 445,
"name" : "Mountain"
} ],
"state" : "CA",
"yearsExp" : 20.0,
"zip" : "94131"
},
{ "SFDCStatus" : "RETRIEVED",
"deleted" : false,
"firstName" : "Daniel",
"id" : 40,
"lastName" : "Adams",
"lastUpdated" : "2011-11-23T05:44:03Z",
"name" : "Daniel Adams"
}
]
Any ideas? Someone told me this was a Salesforce.com bug, but it seems like even if that were true, there must be a workaround.

Looks like you may not be casting properly. I haven't played around with the serialize/deserialize native JSON much yet and have preferred to do my own parsing/persisting. But your line causing the error looks suspicious:
List<FactorLabPullUser> flusers = (List<FactorLabPullUser>)JSON.deserialize(res.getBody(), Type.forname('List<FactorLabPullUser>'));
I think it should look like the following:
List<FactorLabPullUser> flusers = (List<FactorLabPullUser>)JSON.deserialize(res.getBody(), List<FactorLabPullUser>.class);

I can't see for sure from your code snippit but if the FactorLabPullUser class is an inner class you will need to fully qualify it for Type.forName() to work.
I would expect to see something like this:
List<FactorLabPullUser> flusers = (List<FactorLabPullUser>)JSON.deserialize(res.getBody(), Type.forname('List<Outerclass.FactorLabPullUser>'));
I think that the bug you mention is to do with the use of the .class method - I have noticed this not always return a valid Type.

Related

Postman giving me a JSON Bad String Error

I'm new to Postman- I am inserting a report and calling this function with a POST and Body JSON like this:
{
"data": [
{
prmRoadClosures : "I-65",
prmFirstMaintainStart=: "Test_EMS",
prmPSR_AbnormalOperations: "Test AO",
prmFeedstockChanges: "Test FSC",
prmLineupChanges: "Test LC",
prmSafetyMeetings: "Test_SM",
prmAR_SH_ID: 1,
prmAR_RE_ID : 1,
prmCR_AbnormalOperations : "Test AO",
prmHighPriorityAlarms : "Test HPA",
prmImpairment_to_fire_protection_systems : "Test Fire systems",
prmAlarmsInhibited : "test ALARMS",
prmCR_OP_ID : 1,
prmCR_PC_ID : 1,
prmFR_AbnormalOperations : "Test AO",
prmMaintenance : "test M",
prmFR_OP_ID : "1",
prmBP_ID : 1,
prmDP_ID : 1,
prmEQM_ID : 1,
prmCreatedDate : ,
prmUpdatedDate : ,
prmCreatedBy : "HS",
prmUpdatedBy : "HS",
prmShift : "1",
prmArea_ID : 1,
prmUser_ID : 1
}
]
}
the Bad Script error show
prmRoadClosures : "I-65",
to be the offending line. I can't see why I'm getting this error. Is it obvious?
TIA
Harry
That's not JSON Format like previously said.
If you have doubt on json format, you can use a validator like : https://jsonformatter.curiousconcept.com/
It will find error for each row so that's really helpful to find all mistakes.

Getting a dictionary var from parsed json in swift

i'm trying to set all the parsed information in json in a dict variable but it returns an empty dict. when i get the array value, everything works completely fine.
here is my code:
let dic = json.arrayValue
for each in dic {
let data = each["data"].dictionaryValue
print (data)
let date = each["date"].stringValue
print (date)
}
parsing date works fine too. and note that my json file is not empty. because when i get the arrayValue everything is fine. here is the output when i print each["data"].arrayValue:
[{
"factoryPrice" : 0,
"size" : 25,
"t5" : 0,
"t3" : 0,
"type" : 1,
"bongahPrice" : 2435,
"sherkat" : "",
"priceConfirmed" : 1,
"id" : 1658,
"factory" : 9,
"exist" : true,
"t1" : 0,
"provice" : 1,
"properties" : {
"طول" : "12 متری",
"info" : "",
"استاندارد" : "A2",
"standard" : "A3",
"رنگ" : "مشکی",
"نوع" : "آجدار"
},
"factoryName" : "نیشابور",
"city" : 306,
"name" : "",
"phoneNumber" : "09338810407",
"createdAt" : "2018-02-16 12:52:50",
"ownerId" : 282,
"shomareSabt" : "",
"t4" : 0,
"profileType" : 0,
"t2" : 0,
"modirName" : "آرزومند",
"bongahName" : "میلگرد تهران",
"updatedAt" : "11:36",
"weight" : 22,
"group" : 57,
"bongahAddress" : "بازاراهن شادباد بوستان بلوک B",
"bongahPhone" : "02166139083"
}]
and this only one of the arrays. i get multiple arrays in response.
so what should i do?
The JSON you have has an array as its top level element. This is clear by the first character: [.
You can't directly get a dictionary value for your JSON because it represents an array. That's the reason trying to get dictionaryValue returns nil.

MongoDB Change/Update Subdocument Field

I currently have a Mongo DB database with one collection ('locations') with one document:
{
"_id" : ObjectId("5875653b89513c8328416522"),
"name" : "Starcups",
"address" : "125 High Street, Reading, RG6 1PS",
"rating" : 3,
"facilities" : [
"Hot drinks",
"Food",
"Premium wifi"
],
"coords" : [
-0.9690884,
51.455041
],
"openingTimes" : [
{
"days" : "Monday - Friday",
"opening" : "7:00am",
"closing" : "7:00pm",
"closed" : false
},
{
"days" : "Saturday",
"opening" : "8:00am",
"closing" : "5:00pm",
"closed" : false
},
{
"days" : "Sunday",
"closed" : true
}
],
"reviews" : [
{
"author" : "Simon Holmes",
"id" : ObjectId("5875663389513c8328416523"),
"rating" : 5,
"timestamp" : ISODate("2013-07-15T23:00:00Z"),
"reviewText" : "What a great place. I can't say enough good things about it."
}
]
}
I need to alter the field "id" (part of the subdocument reviews) to "_id". I have tried, using other similar examples on StackExchange, the following code to no avail:
db.locations.update({}, {$rename:{"reviews.id":"reviews._id"}}, false, true);
But I receive the following error:
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "cannot use the part (reviews of reviews.id) to traverse the element ({reviews: [ { author: \"Simon Holmes\", id: ObjectId('5875663389513c8328416523'), rating: 5.0, timestamp: new Date(1373929200000), reviewText: \"What a great place. I can't say enough good things about it.\" } ]})"
}
})
I get the same error when I try to alter any other field. Could someone point me in the right direction?
Update:
This seems to be a problem assessing the subdocument field as the following code executes fine:
db.locations.update({}, {$rename:{"name":"names"}}, false, true);
I have also tried searching through the relevant documentation: https://docs.mongodb.com/manual/reference/operator/update/rename/
That's because Reviews is an Array
You cannot $rename to do that , instead you need to $set the new name and $unset the old one

Error importing JSON file in Parse

My current file looks like this:
{
"result": [
{
"Longitude" : "-075.947332",
"Zipcode" : "21922",
"ZipClass" : "STANDARD",
"County" : "CECIL",
"City" : "ELKTON",
"State" : "MD",
"Latitude" : "+39.593612"
},
{
"Longitude" : "-075.884544",
"Zipcode" : "21930",
"ZipClass" : "PO BOX ONLY",
"County" : "CECIL",
"City" : "GEORGETOWN",
"State" : "MD",
"Latitude" : "+39.366183"
}
]
}
I continuously get the following error:
file should have the following format
{ "results": [ {...}, ... ]}
Any ideas whats going on or how I can import my file.
The link to my file is right here for further understanding: http://gomashup.com/json.php?fds=geo/usa/zipcode/state/MD&jsoncallback=?
Note* (There is no "?" in my JSON file like data in above link.)
Looks like you need to change "result" to "results".
The file you linked to begins with a parenthesis ((), that might be an issue too.

Popover is not working for json multiple values

[
{
"id" : 1,
"name" : "clevin",
"description" : "Version 1 : some desc",
"info" : [{
"id" : 2,
"name" : "abc",
"size" : "5 GB",
"used" : "25%"
},
{
"id" : 3,
"name" : "def",
"size" : "10 GB",
"used" : "15%"
},
{
"id" : 4,
"name" : "ghi",
"size" : "20 GB",
"used" : "5%"
}],
}]
This is my json file. When ever i mouse over "info.name"[abc, def, ghi] popover will display "name", "size" and "used".
but my issue is "abc" is the first value , when ever i mouseover it display value as expected. but when i mouseover "def" and "ghi" nothing is happened :(.
<ul type="none">
<li>
<label id="vol-label" class="muted">Info :</label>
{{#info}}
<span id="value"><a><u>{{name}}</u></a></span>
<span id="info-popover-title" class="hide">{{name}}</span>
<div id="info-popover-content" class="hide">
<p>Size : {{size}}</p> <p> Used : {{used}}</p><p> Status : {{status}}</p>
</div>
{{/info}}
</li>
</ul>
This is my template(mustache).
following is my view part(backbone.js)
events: {
"mouseenter #value" : "showDetails",
"mouseleave #value" : "hideDetails" ,
},
showDetails : function() {
this.$("#value").popover({
html : true,
title: function() {
return $("#info-popover-title").html();
},
content: function() {
return $("#info-popover-content").html();
}
});
this.$("#value").popover('show');
},
hideDetails : function() {
this.$("#value").popover('hide');
},
Please see my both screen shot to understand the issue. In fist screens hot see am getting all json info values "abc" "def" and "ghi" . in 2nd screen shot if i mouse over am getting "abc" values. but "def" and "ghi" value is not at all displaying. am not figure it out what is the issue :(.
I need to popove "def" and "ghi" values also. But i think something is wrong in my logic. Thanks in advance. This is really a rare issue for me might be others also.
If i use class insted of id following is the screen shot :(
2 things that you need to change here. First, is to use class to define for popovers instead of id. And the second is to abstract each <li> into its own view. Currently, you have one view that loops through the entire collection. All your events are currently tied to this one view. Doing those things I mentioned should fix this issue.
You can do something like this to have the become its own view which carries it's own sub-element. Just wrote this quickly and haven't tested but the idea is something like this. I'm not really sure which popover library you're using but the idea is generally the same.
Edit: Didn't realized you were using Mustache/Handlebars, so here's the JS Fiddle. Code
Now if you try to call each object it should work.
var abc =
{
"id" : 1,
"name" : "clevin",
"description" : "Version 1 : some desc",
"info" : {
"id" : 2,
"name" : "abc",
"size" : "5 GB",
"used" : "25%"
}
};
var def =
{
"id" : 3,
"name" : "def",
"size" : "10 GB",
"used" : "15%"
};
var ghi = {
"id" : 4,
"name" : "ghi",
"size" : "20 GB",
"used" : "5%"
};
var output =
{
show : function()
{
return abc["info"];
}
};
console.log(output.show());