i have json string like this downbelow
{"0":{"in":"mmm","loc":"1234"},"1":{"in":"mmm","loc":"1234"}}
Now i need to parse them as like
in | loc
---------
mmm| 1234
mmm| 1234
So far i did
public with sharing class Search
{
public String strTag {get;set;}
public String strlocation {get;set;}
public String result {get;set;}
public PageReference find() {
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('http://test.3spire.net/index.php?in='+strTag+'&loc='+strlocation);
req.setMethod('GET');
//these parts of the POST you may want to customize
req.setCompressed(false);
req.setBody('key1=value1&key2=value2');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
try {
res = http.send(req);
} catch(System.CalloutException e) {
system.debug('Callout error: '+ e);
result = ''+e;
}
Result results = (Result) JSON.deserialize(res.getBody(),ResultSet.class);
result = res.getBody();
system.debug(res.getBody());
return null;
}
public class ResultSet{
public List<Result> resultSet;
}
public class Result
{
public String ins;
public String loc;
}
}
But its returns
System.TypeException: Invalid conversion from runtime type Search.ResultSet to Search.Result
How can i solved this problem
Thanks in advance
You are calling JSON.deserialize(res.getBody(),ResultSet.class). The second parameter ResultSet is the Apex object type you want the result to be. But then you attempt to cast it to a type of Result instead.
Either do
Result results = JSON.deserialize(res.getBody(), Result.class);
or
ResultSet results = JSON.deserialize(res.getBody(), ResultSet.class);
In your case, based on the JSON it would seem you want the second option. However, your JSON doesn't quite match your ResultSet class either. Your JSON is a map, not a list. Also, there's a field mismatch between "in" and "ins". This JSON is what would match your ResultSet class:
{{"ins":"mmm","loc":"1234"},{"ins":"mmm","loc":"1234"}}
Related
I am calling a third-party API that returns two different values for the same parameter name as below,
ActivationResponse activationResponse = new ActivationResponse();
ResponseEntity<ActivationResponse> response = null;
response = restTemplate.exchange(Url, HttpMethod.POST, request, ActivationResponse.class);
activationResponse = response.getBody();
Error response:
{
"executionCode":"2",
"executionMessage":"NullPointerException Occured!",
"response":"java.lang.NullPointerException"
}
Success response:
{
"executionCode" : "0",
"executionMessage" : "SUCCESS",
"response" : {
"orderID" : "79966036"
}
}
As the sample response response parameter can come as a string or with a JSON object.
Currently the response model is as below,
public class ActivationResponse {
private String executionCode;
private String executionMessage;
private ActivationResponseDetails response;
}
public class ActivationResponseDetails {
private String orderID;
}
When the error comes, an exception is thrown indicating that it can't handle the response parameter. Please advice how to handle both success and failure scenarios without issues.
Please Note that approach in this answer is not possible, because I have to print the logs in following way, so using #JsonIgnore will not show that parameter on the log.
Logs are printed like this,
log.info("ActivationResponse json : {}", mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getBody()));
If you insist on having a one-size-fits-all Response object, setting the type of the response field to Object, may do the trick:
public class ActivationResponse {
private String executionCode;
private String executionMessage;
private Object response;
}
The field 'response' should now resolve to a simple String (success) or a more involved Java object (error).
I am sending this as body from postman : "userId":"11" .
#PostMapping(value="/logout",consumes = "application/json")
public void logout(#RequestBody String userId){
ordersService.logout(userId);
}
Then return holds userId= "{\r\n "userId":"11"\r\n}" ,but i just want to get the value 11.I dont want to get the key. How can I do that?
This should do the work
#RequestMapping(
path = "/logout",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public void logout(#NotNull #RequestBody Long userId)
{
ordersService.logout(userId);
}
I am trying to check if the response from the API GET method is Null. The response is like
{
"#odata.context": "https://dev.com/data/$metadata#Customers",
"value": []
}
I need to check if the value array is null or not and do the necessary steps below is what I tried
public class deserializeData
{
public String #odata_context {get;set;} // in json: #odata.context
public List<Value> value {get;set;}
}
public class getDataFromExternalSystem{
public string getDataFrom(){
.......
Http http1 = new Http();
HttpRequest req1 = new HttpRequest();
req1.setEndpoint(endPoint);
req1.setMethod('GET');
req1.setHeader('Authorization','Bearer '+atoken);
HttpResponse res1 = http1.send(req1);
System.debug('Response Body=========' + res1.getBody());
deserializeData dsData = (deserializeData)JSON.deserialize(res1.getbody(),deserializeData.class);
if(dsData.value.size = null) {
......
}
else{
......
}}
But I get below error like
#odata_context is not a legal identifier in Apex. # is used to introduce annotations.
If you're using JSON2Apex, which appears to be the case, you'll need to change the name of the property to something legal for Apex (like odata_context), and make the corresponding change in the parser method. E.g., where JSON2Apex generates
if (text == '#odata.context') {
#odata_context = parser.getText();
you'll need to replace that identifier with the new one you choose.
First off my question is very similar to below however I'm not sure if the answers are applicable to my specific problem or whether I just need clarification about how to approach it:
Convert LinkedHashMap<String,String> to an object in Java
I am using struts2 json rest plugin to convert a json array into a java array. The array is sent through an ajax post request and the java receives this data. However instead of being the object type I expect it is received as a LinkedHashmap. Which is identical to the json request in structure.
[
{advance_Or_Premium=10000, available=true},
{advance_Or_Premium=10000, available=true},
{advance_Or_Premium=10000, available=true}
]
The data is all present and correct but just in the wrong type. Ideally I want to send the data in my object type or if this is not possible convert the LinkedHashMap from a list of keys and values into the object array. Here is the class I am using, incoming data is received in the create() method:
#Namespace(value = "/rest")
public class OptionRequestAction extends MadeAbstractAction implements ModelDriven<ArrayList<OptionRequestRest>>
{
private String id;
ArrayList<OptionRequestRest> model = new ArrayList<OptionRequestRest>();
public HttpHeaders create()
{
// TODO - need to use model here but it's a LinkedHashmap
return new DefaultHttpHeaders("create");
}
public String getId()
{
return this.id;
}
public ArrayList<OptionRequestRest> getModel()
{
return this.model;
}
public ArrayList<OptionRequestRest> getOptionRequests()
{
#SuppressWarnings("unchecked")
ArrayList<OptionRequestRest> lReturn = (ArrayList<OptionRequestRest>) this.getSession().get("optionRequest");
return lReturn;
}
// Handles /option-request GET requests
public HttpHeaders index()
{
this.model = this.getOptionRequests();
return new DefaultHttpHeaders("index").lastModified(new Date());
}
public void setId(String pId)
{
this.id = pId;
}
public void setModel(ArrayList<OptionRequestRest> pModel)
{
this.model = pModel;
}
// Handles /option-request/{id} GET requests
public HttpHeaders show()
{
this.model = this.getOptionRequests();
return new DefaultHttpHeaders("show").lastModified(new Date());
}
}
One of the things which is confusing me is that this code works fine and returns the correct object type if the model is not an array. Please let me know if my question is not clear enough and needs additional information. Thanks.
I need to parse this json string to values.
"start": { "dateTime": "2013-02-02T15:00:00+05:30" }, "end": { "dateTime": "2013-02-02T16:00:00+05:30" },
The problem is I am using JSONParser in apex (salesforce).
And my class is:
public class wrapGoogleData{
public string summary{get;set;}
public string id{get;set;}
public string status;
public creator creator;
public start start;
public wrapGoogleData(string entnm,string ezid,string sta, creator c,start s){
summary= entnm;
id= ezid;
status = sta;
creator = c;
start = s;
}
}
public class creator{
public string email;
public string displayName;
public string self;
}
public class start{
public string datetimew;
}
I am able to get all the datat from this except the datetime in the above string. As datetime is a reserved keyword in apex so i am not able to give the variable name as datetime in my class.
Any suggestion !!
Json Parser code:
JSONParser parser = JSON.createParser(jsonData );
while (parser.nextToken() != null) {
// Start at the array of invoices.
if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
while (parser.nextToken() != null) {
// Advance to the start object marker to
// find next invoice statement object.
if (parser.getCurrentToken() == JSONToken.START_OBJECT) {
// Read entire invoice object, including its array of line items.
wrapGoogleData inv = (wrapGoogleData)parser.readValueAs(wrapGoogleData.class);
String s = JSON.serialize(inv);
system.debug('Serialized invoice: ' + s);
// Skip the child start array and start object markers.
//parser.skipChildren();
lstwrap.put(inv.id,inv);
}
}
}
}
Similar to Kumar's answer but without using an external app.
Changing your start class was the right idea
public class start{
public string datetimew;
}
Now, just parse the JSON before you run it through the deserializer.
string newjsondata = jsonData.replace('"dateTime"','"datetimew"');
JSONParser parser = JSON.createParser(newjsondata);
while (parser.nextToken() != null) {
...
}
Use string.replace() function and replace keys named dateTime with something like dateTime__x and then you can parse using Json.deserialize if you have converted your json to apex using json to apex convertor app on heruko platform
http://json2apex.herokuapp.com/
The above link points to an app that will convert Json into apex class and then you can use Json.serialize to parse json into apex class structure.