Hot answers tagged

29

The Salesforce JSON.deserialize(String, Type) method cannot deserialize from JSON into generic Object, or into objects with generic Object fields, it can only deserialize into concrete types with fields that have concrete type. Everywhere the you have defined your field types as Object, e.g. public Object CellphoneNumber, you need to replace Object with the ...


12

If the JSON is reasonably small then I would build it in the unit tests. That allows you to generate various permutations and always have the values to hand to assert against. The best way to do that (when you don't have Apex classes generated by e.g. JSON2Apex) is by creating nested Map<String, Object>s and then applying JSON.serialize. This ensures ...


7

For this situation, I would use JSON.deserializeUntyped that returns nested maps (for objects) and lists (for arrays). That allows the platform code to deal with all JSON related issues (such as escaping and syntax checking) without you having to write any code (such as the hard to get right nextToken stuff). Your job is then to check what is in the maps -...


6

There is no quick and easy way to transform XML either into JSON or into an Apex Class. I came up against this in a recent project, and I ended up using the Dom.Document and Dom.XmlNode classes. There's likely a way to abstract this pattern, but the basic idea that I used was to have an outer class to start the parsing, and then have a bunch of inner ...


6

Once you add the curly brackets, your JSON looks like this { [ { \"sampleNumber\":\"WO-02609\", \"SampleID\":\"a3F5C000000CHATTAM\", \"state\":\"Open\" } ] } Which is invalid JSON because you have an list inside of an object without a property name. Instead of adding the curly brackets, change your code to deserialize the JSON ...


5

String resPostalCode; Since your string is null, += causes the code to expand to: resPostalCode = null + '10019-6019'; Instead, make sure your string isn't null first: Sring resPostalCode = ''; You can void silly mistakes like this by using the more reliable JSON.deserialize method instead. public class Address { public String Address1, Address2, ...


5

I think the issue is that you are not advancing the parser after saving the ParsedId. Let's say that the if statement for the Id is evaluated as true. You then save the ParsedId, but you are not advancing the parser forward afterwords. That means the second If statement can never be true because the parser is still pointing to the value of the Id.


4

Don't bother using JSONGenerator. It's particularly error prone and slower than just serializing a map. Here's an example of serializing a map: JSON.serialize( new Map<String, Object> { 'element1' => '123123', 'element2' => 'test', 'element3' => new Object[] { new Map<String, Object> { 'element3.1' => ' ', ...


4

The trailing "," is not allowed. The final element in an object or array must not have a comma after it. { "PId" : "345", "Description" : "test", "Codes" :[ { "Code" : " ", "qw" : " ", "qwe" : " ", "Desc" : " ", "RT": " " } ], "AccountName" : "Account 001", "AccountNumber" : "123333" , "Address" : "NY" }


4

There are two resource that will help you out tremendously here: JSON - understand the spec JSONLint - validate specific payloads JSON2Apex - verify corresponding Apex Your payload is not in a valid format for several reasons. Here is the immediate JSONLint Result: Results Error: Parse error on line 3: ...Nuclear_Agreement", ]] ----------------------...


4

"myMethod" didn't work because of compilation errors. Here's what it really should look like: for (AgentInfoList agentItem : myParsedResult.AgentInfoList){ un.add(agentItem.Username); pn.add(agentItem.PriorityNumber); } But that's overkill; AgentInfoList already has the data you need, so if you'd simply started off with that as a public ...


4

You seem to have a typo in your class. cecDocumentRetrievalResponse() should be DocumentRetrievalResponse() If I use your same DocumentRetrievalResponse class, remove the cec and use your JSON I can run your lines and it works for me. I made no changes to your code. String result = '{"searchDocumentsResponse": {"documentsIndexInfo": [{"...


3

JSON class has deserializeUntyped method that converts JSON to map. Sample code: String jsonInput = '{"email":"are02@gmail.com","LastName":"ABCD","FirstName":"ACFPY","Suffix":"","Title":"Engineer","Psw":"","PhoneCode":"","Phone":"100-000-000"}'; Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(jsonInput); You can read more ...


3

If you mean you want to look at the bytes that make up the file using Apex code you can't directly. You can turn it into a base64 string using EncodingUtil.base64Encode but as the string characters then don't align with the byte boundaries it is very hard work to do anything useful (and you are likely to run into CPU and heap governor limits). So if you ...


3

Your wrapper class and related classes need to look like this: public class Location { } public class Company { public Integer id; public String industry; public String name; public String size; public String ticker; public String type; } public class Values { public Company company; public Integer id; public Boolean ...


3

If would write that like this: Map<String, String> tokenCredMap = new Map<String, String>(); String tokencred = '[{"Id":"003m000000yKLySkkL","Token":"I2j5bUky04B4eLJGYELV"}]'; List<Object> items = (List<Object>) JSON.deserializeUntyped(tokencred); for (object item : items) { Map<String, Object> typedItem = (Map<String, ...


3

You can use JSON2Apex tool, which can help generate strongly typed Apex code for parsing a JSON structure given an example of the JSON. JSON2Apex public class JSON2Apex { public class Weather { public Integer id; public String main; public String description; public String icon; } public class Coord { ...


3

Your class passes the wrong string to JSON.deserialize(). public static MyJSON parse(String json){ String jsonReplace = json.replace('"currency":', '"currencyRep":'); jsonReplace = jsonReplace.replace('"number"','"numberRep"'); return (MyJSON) System.JSON.deserializeStrict(json, MyJSON.class); You're transforming the string, but then ...


3

My first question - what does this output mean? This output tells you two things: first, it is a delegate object, meaning that the actual implementation is written in Java (common.apex.json.ApexJsonParser). Apex is essentially a Virtual Machine inside a Virtual Machine, where some types of objects and methods are marshalled by the runtime. If you're really ...


3

When you use deserializeUntyped(), you get an Object back, which is usually either cast to Map<String, Object> or List<Object>. The thing that you're missing here is that each object that you get from your Map or List can also be cast. Applying this to your loop, we get for(Object each : received){ Map<String, Object> nextLevel = (...


3

I would really advise you not to do this. Apex in its current form is really not suited for parsing and - more importantly - user-generated SOQL strings is a big security red flag. I know it's probably not the answer you wanted, but my advice would be to have a user-generated object-representation of the query (for example, an object representation of the ...


2

Try doing - Create a custom setting for your countries list & Salesforce timezone id's i.e.(London -> Europe/London) Using the Timezone Id above get the timezone something like - TimeZone tz = TimeZone.getTimeZone('Europe/London'); Create a Date/Time instance of the date & time selected DateTime dtpost = DateTime.newInstanceGMT(2012, 11, 1, 0, 0, 0);...


2

A simple class to illustrate this would be: public class myExampleObject{ public String field1; public String field2; public myChildObject[] children; public class myChildObject{ public string childField1; public string childField2; } } Then you could simply populate as follows (may require debugging, writing ad ...


2

You would add each as a separate Map<String, Object>: 'children' => new List<Object> { new Map<String, Object> { 'Name' => 'Child 1', 'SomeField__c' => 'Some Value' }, new Map<String, Object> { 'Name' => 'Child 2', 'SomeField__c' => 'Some Other Value' } }


2

It would be most sensible to use an existing tool of which there are a number. I do not have experience of using any of these so you would need to do further research. Open source Andrew Fawcett's Apex-CodeAnalysis tool - open source so can be customised to fit requirements and would be free to use. Commercial Clayton - I have seen this demoed, but not ...


2

I would suggest using Force.com IDE plugin for Eclipse, which gives you more detailed error message about syntax error. Also you can try use other third-party applications which allow you to perform SOQL like workbench or Schema Viewer. I would agree that error from Developer Console is not the error which we would like to see, probably you can either log a ...


2

Unless the XML is very large, reading the XML into a DOM is the way to go. If an element is missing you need to first check for that before trying to get the text of the element. So change: oResponse.Message = response.getChildElement('Message', null).getText(); to: Dom.XmlNode message = response.getChildElement('Message', null); oResponse.Message = ...


2

This looks like a Python object returned by the suds package, which is what the Fuel-SDK uses to make SOAP requests. If the code snippet you posted is what is stored in response.Results, you should be able to access the values like this: for send in response.Results: print send.SendDate Or like this: print response.Results[0].SendDate If you want ...


2

You'll want a batch process to parse the classes, because of the potential of hitting CPU limits. You can start your batch off like this: public ApexClass[] start(Database.BatchableContext context) { return [SELECT Body FROM ApexClass]; } You can't retrieve the body from protected classes (those that are managed and not global). Parsing Apex Code would ...


2

My New code to read and insert data from a csv file using the salesforce email service Global class CSVFileDataImportEmail implements Messaging.InboundEmailHandler { Global string nameFile{get;set;} Global blob contentFile{get;set;} String[] filelines = new String[]{}; Boolean processSheet = True; List<Supplier_Capacity__c> ...


Only top voted, non community-wiki answers of a minimum length are eligible