I am working on the requirement where a User can fetch the data from production box and insert it into developer sandbox by just giving production URL and creds. I am able to fetch data but somehow not able to convert the JSON to required object type. As I am newbie in Salesforce please don't mind for basic questions.
Below is the working logic and issue:
for(DataMigrationNAP__c d : dataMigrationNAP) // this loop will give all NAP object names and its corresponding fields like {'Account','Name,Phone,Id'},{'Opportunity', 'ID,Name, blah,blah'}...
{
final PageReference theUrl = new PageReference(SERVER_URL + '/services/data/v22.0/query/');
String soql = 'Select '+d.NAPObjectFields__c+' From '+d.Name+' a limit ' + recordCount;
theUrl.getParameters().put('q',soql);
request = new HttpRequest();
request.setEndpoint(theUrl.getUrl());
request.setMethod('GET');
request.setHeader('Authorization', 'OAuth ' + SESSION_ID);
String body = (new Http()).send(request).getBody();
JSONParser parser = JSON.createParser(body);
do{
parser.nextToken();
}while(parser.hasCurrentToken() && !'records'.equals(parser.getCurrentName()));
parser.nextToken();
String typeName = 'List<' + d.Name + '>';
Type t = Type.forName(typeName);
List<sobject> acc1 = (List<sobject>) parser.readValueAs(t);
insert acc1;
System.debug('Values inserted : ' + acc1);
}
Through above logic I am trying to fetch the data Object by Object and insert it into dev sandbox, I am able to fetch perfectly in JSON but not able to convert from JSON to required object. The issue is I can't hardcode Object or Type name because it will be a list of objects. Please let me know if you need any other detail and thanks in advance. Open for any other approach as well but it should be through apex coding only.
Have you tried JSON2Apex already, if not than this could be good candidate.
Related
I am trying to filter JSON data with my Arduin (working with an ESP8266).
This is what I have :
if (httpCode > 0) {
// Parsing
const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
DynamicJsonBuffer jsonBuffer(bufferSize);
JsonObject& root = jsonBuffer.parseObject(http.getString());
// Parameters
int id = root["Reismogelijkheid"];
const char* departure = root["ActueleVertrekTijd"];
// Output to serial monitor
Serial.print("Vertrijktijd:");
Serial.println(departure);
}
I can make connection to my wifi network and I can make connection to the website to get JSON data from here : http://hendriks.pm/ns.php but I want to filter the data and only get the ActueleVertrekTijd, so that I can store it in a const and that I can see it on my Serial monitor.
I tried to use this example : https://www.instructables.com/id/ESP8266-Parsing-JSON/ but that didn't worked for me.
This is the Json :
Hello and welcome to Stackoverflow,
The problem is that you dont traverse trough the JSON.
If you want to retreive a value of an Object you should use
root["Reismogelijkheid"]["ActueleVertrekTijd"]
or if it is consistent:
root["Reismogelijkheid"][5]
instead of
root["Reismogelijkheid"]
This will give you the value that you want.
EDIT
For more information about parsing JSON you can use this site:
https://randomnerdtutorials.com/decoding-and-encoding-json-with-arduino-or-esp8266/
Here is my code
I am trying to insert Json values into Azure as Entity, but I always get only the first value when I get back from Azure..Is there anything I need to change in the below code?
string Emulators = "['TestEmulator1','Testemulator12','Testemulator2','TestEmulator3']";
List<string> Emulators = new List<string>();
EmulatorIDS.Add(Emulators);
var jsondata = JsonConvert.SerializeObject(Emulators);
Console.WriteLine(jsondata);
var EmulatorID = new EntityProperty(jsondata);
//Instantiate serializer
Random rnd = new Random();
int a = rnd.Next(1, 1000);
DynamicTableEntity actordata = new DynamicTableEntity();
actordata.RowKey = "Test"+a.ToString();
actordata.PartitionKey = "test#gmail.com";
actordata.Properties["DetailsValue"] = EmulatorID;
actordata.Properties["OtherData"] = EmulatorID;
TableOperation insertOperation = TableOperation.Insert(actordata);
table.Execute(insertOperation);
Have a look https://www.nuget.org/packages/ObjectFlattenerRecomposer/ version 2.0 it will automatically convert your complex objects to a writable form to table storage, it supports complex types and ICollection/IEnumerable type properties as well. You do not need to do any up front json conversion yourself either, the api automatically handles conversions.
If anybody is looking for answer for this..Please see here about how to insert Json values via TableEntity instead of using JsonPayload format
I'm trying to parse JSON data from URL and show the data in my app.
JSON Example (After accessing specific URL):
[{"placeID":"1","placeName":"Test Place","city":"New York","type":"Rest"..
How I can read this data and show a list of the places recieved from the API?
I've been trying ALL of the guides over the internet for parsing JSON data from URL with Android Studio and without. As a total beginner with Android developement, I couldn't make one working exmaple with json even when the author shared the final example for download. I hope you can help me in noob-friendly way and step by step or refer me to the right places.
Thank you!
I believe Android uses org.json as the JSON library, in which case something like this works to retrieve information about each place (assuming data is a valid JSON string)
try {
String data = "\"[{\"placeID\":\"1\",\"placeName\":\"Test Place\",\"city\":\"New York\",\"type\":\"Rest\"..";
JSONArray places = new JSONArray(data);
for (int i = 0; i < places.length(); i++)
JSONObject place = (JSONObject) places.get(i);
int id = place.getInt("id");
String name = place.getString("placeName");
String city = place.getString("city");
// etc...
// Do what you wish with the id, name, city and other variables.
// It loops through here for each item in the JSON variable.
}
} catch (JSONException e) {
e.printStackTrace();
}
This goes through each place in the JSON array and grabs some of the variables from it. It would probably be smart to create a data class and call it something like Place. You could then pass in the data with a constructor: new Place(id, name, city); (see this constructor for example: https://stackoverflow.com/a/22419370/5236779).
I am working on a WP8 app. In this I need to connect to web services whose results will be some JSON. I was trying to extract some data from the result that the web service provide. I was able to extract from the initial JSON response. But I need to get some data from the value of one such key . SO I tried to generate another Json object from it. But I m stuck. please help.Please find my example code below(I am using Newtonsoft.JSon).
private void messages_buttons_Click(object sender, RoutedEventArgs e)
{
var str = "{'status': '0', 'result': '%7B%22campaign_id%22%3A%221%22%2C%22tfn%22%3A%2218773374136%22%2C%22campaign_code%22%3A%22PJC%22%2C%22ad_id%22%3A%221%22%2C%22qr_url%22%3A%22http%3A%5C%2F%5C%2F1d1.us%5C%2FPJC%5C%2F%22%2C%22campaign_name%22%3A%22PJ+Test+Campaign%22%2C%22is_active%22%3A%221%22%2C%22expire_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22start_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22alias%22%3A%22%22%2C%22icon_image_url%22%3A%22products%5C%2Fpjc%5C%2Fpjc3.jpg%22%2C%22fb_page_url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com%5C%2FJackLaLannePowerJuicerssfb%22%2C%22video_url%22%3A%22http%3A%5C%2F%5C%2Fyoutube.com%5C%2Fembed%5C%2FyZPedpRA9r0%3Fshowinfo%3D0%26autoplay%3D1%26loop%3D1%26playlist%3DyZPedpRA9r0%22%2C%22url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com'}";
JObject ne = JObject.Parse(str);
var x= (ne.GetValue("result")).ToString();
var z = x.Replace("%", "");
JObject newest = JObject.Parse(z);
var y = newest.GetValue("campaign_id");
MessageBox.Show(y.ToString());
}
I get an exception at "JObject newest = JObject.Parse(z);" with the message
Unexpected character encountered while parsing number: m. Path '', line 1, position 6.
Am I doing it entirely wrong?
On a general note: can I convert a value from one Json to a another JSOn Itself? i.e if the value of one json key is a string with some key value pairs, can i make a json object on that string?
You can't actually just remove the % chars to get a valid value. You need to decode the string.
If you use this:
HttpUtility.UrlDecode(x);
You'll find your "result" is actually invalid JSON:
{"campaign_id":"1","tfn":"18773374136","campaign_code":"PJC","ad_id":"1","qr_url":"http://1d1.us/PJC/","campaign_name":"PJ
Test Campaign","is_active":"1","expire_on":"2021-05-05
00:00:00","start_on":"2021-05-05
00:00:00","alias":"","icon_image_url":"products/pjc/pjc3.jpg","fb_page_url":"https://www.facebook.com/JackLaLannePowerJuicerssfb","video_url":"http://youtube.com/embed/yZPedpRA9r0?showinfo=0&autoplay=1&loop=1&playlist=yZPedpRA9r0","url":"https://www.facebook.com
So hacking the value to make it valid JSON might work for you, by adding the missing "} at the end should turn your value in to valid JSON and allow you to parse it.
JObject newest = JObject.Parse(x + "\"}");
var y = newest.GetValue("campaign_id");
It doesn't appear that z is a valid json object at this point. It is only the value of result. Try something like JObject.Parse("'result':" + z);
I am using App42 for my mobile backend. I need to put date field in my JSON that I am saving and further do a query on it for date search. I am not able to find it in document. Can anybody please let me know what is the required date format to do this?
You are not mentioned that which SDK you are using.
I am posting an Android sample code for date search in App42 json storage.
String yourDate = Util.getUTCFormattedTimestamp();
JSONObject jsonData = new JSONObject();
jsonData.put("name", "sachin");
jsonData.put("DOB", yourDate);
// Inserting json document.
Storage storageObj = storage.insertJSONDocument("dbName", "collectionName", jsonData);
System.out.println(storageObj);
// building query.
Query query = QueryBuilder.build("DOB", yourDate, Operator.EQUALS);
// find documents by query.
Storage result = storage.findDocumentsByQuery("dbName", "collectionName", query);
System.out.println(result);