I have been searching quite a while now for how to read a nested JSON with C++ Builder XE2 TJSONObject.
There are a few examples in Delphi but they use the TJSONValue object, but in the C++ version this class has a pure virtual function and can not be created.
Some example JSON:
{
"totalHits": 4170,
"totalCount": 4170,
"startIndex": 0,
"adverts": [
{
"Id": "14380005",
"companyInfo": {
"companyName": "Clarion Hotel Sign",
"orgNumber": "5564660107",
"companyText": "hotell"
},
"address": {
"streetName": "Street race 2",
"postCode": "101 26",
"postArea": "MY AREA",
"postBox": "Box 310"
},
"homepage": "www.mypage.net"
}
]
}
The whole JSON is stored in the JSON object, trust me, it's in there :)
TJSONObject *JSON = new TJSONObject;
I have no problem to get the value for totalHits and totalCount, but how do I get the "companyName" value?!?
Thanks
I post this belated answer for someone else who meets the same problems in the future....
TJSONArray* jArray = (TJSONArray* )JSON->Get("adverts")->JsonValue;
TJSONObject* jCompanyInfo = (TJSONObject*)((TJSONObject*)jArray->Get(0))
->Get("companyInfo")->JsonValue);
String companyName = jCompanyInfo->Get("companyName")->JsonValue->Value());
Related
I want to get posts from Reddit API. Posts are in "children" node but each object has another object inside.
Can somebody help me write a function that convert this JSON to a list of dart objects?
Here is JSON string.
{
"kind": "Listing",
"data": {
"after": "t3_zzzhq4",
"dist": 2,
"children": [
{
"kind": "t3",
"data": {
"selftext": "blablabla",
"author_fullname": "3xblabla",
"title": "moreblabla",
"created": 1672515982,
"id": "10020p0"
}
},
{
"kind": "t3",
"data": {
"selftext": "blablabla",
"author_fullname": "3xblabla",
"title": "moreblabla",
"created": 1672515982,
"id": "10020p0"
}
}
],
"before": null
}
}
I tried all the tutorials on the topic of complex json parsing, but none of them met my needs. I would know how to parse simple json, but here it is deeply nested JSON, which bothers me a lot, and i cant quite grasp it. Appreciete any help.
Solution:
First go to json to dart and paste JSON string, this generator will make you all classes needed for your JSON.
Then you will need to decode string:
final jsonResponse = json.decode(jsonString);
And then deserialize your JSON like this:
List postslist = list.map((i) => Post.fromJson(i['data'])).toList();
For me, it was crucial i['data']. After adding that, i could deserialize all objects that were living inside that node. Thanks everyone! Hope that someone else this will be helpful! Cheers.
I can't access my JSON model which has been defined in the manifest.json.
My JSON data "zCatsTestJ" looks like this:
{
"d": {
"results": [{
"status": "30",
"skostl": "6210",
"catshours": "2.50",
"ktext": "-",
"counter": "000003484040",
"mandt": "101",
"pernr": "00015822",
"usrid": "-",
"workdate": "\/Date(1477267200000)\/",
"raufnr": "6000025",
}, {
"status": "30",
"skostl": "6210",
"catshours": "2.50",
"ktext": "-",
"counter": "000003484040",
"mandt": "101",
"pernr": "00015822",
"usrid": "-",
"workdate": "\/Date(1477267200000)\/",
"raufnr": "6000025",
}]
}
}
The model seems to be accesible as sJsonDate1 is showing me the data in the console but I can't access a single date. In the end I want to loop over those dates and change the formatting.
var sJsonDate1 = this.getOwnerComponent().getModel("zCatsTestJ");
var sJsonDate2 =this.getOwnerComponent().getModel("zCatsTestJ").getProperty("/d/results/1/workdate");
console.log(sJsonDate1);
console.log(sJsonDate2);
Here is the console output where I can see the complete data.
Console sJsonDate1
But when I try to access one datapoint it says undefined
Console sJsonDate2
I have also instatiated the Model directly in the component and it is working fine. When I compare the model object from getOwnerComponent() and the new one they are nearly the same except for the local one having no aBindings
Model comparison in console
Any help will be highly apreciated. Thanks
Your JSON is invalid, status is missing " and you never close the array. I tried it locally after correcting your JSON and it worked fine on my end.
var json = {
"d": {
"results": [
{
"status": "30",
"skostl": "6210",
"catshours": "2.50",
"ktext": "-",
"counter": "000003484040",
"mandt": "101",
"pernr": "00015822",
"usrid": "-",
"workdate": "\/Date(1477267200000)\/",
"raufnr": "6000025",
}, {
"status": "30",
"skostl": "6210",
"catshours": "2.50",
"ktext": "-",
"counter": "000003484040",
"mandt": "101",
"pernr": "00015822",
"usrid": "-",
"workdate": "\/Date(1477267200000)\/",
"raufnr": "6000025",
}]
}
};
var myModel = new JSONModel(json);
this.getView().setModel(myModel, "test");
this.getView().getModel("test").getProperty("/d/results/1/workdate"); "/Date(1477267200000)/"
Here is the solution. Somehow the JsonModel was too big (667 Data Points) and wasn't loaded on the time of calling it. That's why it has worked with only two entries.
myModel.attachRequestCompleted(function() {
var sJsonDate = myModel.getProperty("/d/results/1/workdate");
console.log(sJsonDate);
});
I'm being driven insane because I can't parse this json response. I've tried many different things and nothing works properly... Could you help me?
The this is the file I am parsing:
{
"info": {
"funds": {
"asset": {
"net": "12516.000",
"total": "0"
},
"borrow": {
"btc": "0",
"cny": "0",
"ltc": "0"
},
"free": {
"btc": "0",
"cny": "0",
"ltc": "0",
"eth": "0"
},
"freezed": {
"btc": "0",
"cny": "0",
"ltc": "0",
"eth": "0"
},
"union_fund": {
"btc": "0",
"ltc": "0"
}
}
},
"result": true
}
I just want something like:
#What I want to get the "net" which is "12516.000", so I tried this:
funds = response['info']['funds']['asset']['net']
funds = response[0] returns { as answer, and funds = response[1] gives me r as a response, and finally if I try funds = response['info'] I get this type error: TypeError: string indices must be integers
You haven't actually parsed the JSON, it's just being read as a string, so response[0] returns the first character of the JSON string, or {. To parse the JSON string,
import json
json.loads(response)['info']['funds']['asset']['net']
which is the pattern you're expecting. More details about the json library can be found here.
I appreciate the answer of #kevmo314.
Sometimes your response may contain leading and trailing whitespaces. You can remove it using strip().
Note: when you get response, basically you get as a string (in some cases, it may be different) which can represent Python objects like list, dictionary etc.
So it's necessary to convert them back into their original form before performing any operations on them.
Below is the working code.
import json
response = response.strip()
response = json.loads(response)
funds = response["info"]["funds"]["asset"]["net"]
print(funds)
I am working with an API that requires the json key value pairs to be ordered when creating resources. The API provides a method (called new) that allows you to make a GET request that will return an object model. I would like to update the model with values within my RobotFramework test cases. Is there a native way within Robot Framework to make a GET request and preserve the json object order sent by the server? Here's an example of the JSON response to the GET new method:
{
"account": {
"#id": "",
"#uri": "",
"#oldID": "",
"person": {
"#id": "",
"#uri": ""
},
"accountType": {
"#id": "",
"#uri": "",
"name": null
},
"accountName": "",
"createdDate": null,
"createdByPerson": {
"#id": "",
"#uri": ""
},
"lastUpdatedDate": null,
"lastUpdatedByPerson": {
"#id": "",
"#uri": ""
}
}
}
If I use the following, the key values automatically get sorted:
${r}= GET Request MySession /accounts/new
For anyone else who needs ordered JSON in robot framework, I was able to achieve it with the following (thanks to help in the comments):
&{object}= Evaluate json.loads('''${r.text}''', object_pairs_hook=collections.OrderedDict) modules=json, collections
Though, ultimately this kind of logic is probably best suited in a custom helper library.
I receive from a webservice, the following JSON:
[ {"lat": 42.41375, "user_id": 762, "user": "John", "lng": 23.02187}, {"lat": 42.46835, "user_id": 675, "user": "Mike", "lng": 23.02612}, {"lat": 42.85672, "user_id": 654, "user": "Jane", "lng": 23.01029}, {"lat": 42.46876, "user_id": 687, "user": "Luke", "lng": 23.02676} ]
I want to add this information using VB.net, row by row, to a DataGridView.
I'm new to JSON.net.
How to loop through the whole list?
How to go about parsing it?
As per as my knowledge there are multiple ways to do it, i prefer following way which is more easy ,straight and maintainable
there is JSON serializer and deserializer provided inbuilt in .net framework, requirement for that is, you have to create classes which will map to your JSON. you can have a look at or http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.deserialize.aspx
In the above case you have to create your class like below
class UserLatLang
{
public long lat { get;set;}
public long lng { get;set;}
public long user_id {get;set;}
public string user {get;set;}
}
after this you can
var serializer = new JavaScriptSerializer();
var listofUserLatLang = serializer.Deserialize<UserLatLang>(responseText);
and you will get a list of UserLatLang in listofUserLatLang
or you can also refer class from http://msdn.microsoft.com/en-us/library/bb412179.aspx
Once you get list of UserLatLang you can directly bind it to DataGrid
Hope this solves your problem
thanks,
Sandesh Daddi