Build Model In Dart For This Form Of Json - json

how I can parse this form of json ?
Where "Question" is an object and not an array, the number of elements within it is not fixed but is related to the length of "question_ids" and the key of each object within it is taken from "question_ids"
{
"questions": {
"96292": {
"correct": false,
"mark": 0,
"answered": ""
},
"96293": {
"correct": false,
"mark": 0,
"answered": ""
},
"96294": {
"correct": false,
"mark": 0,
"answered": ""
}
},
"question_ids": [
96292,
96293,
96294
]
}

just copy and paste your json model to https://javiercbk.github.io/json_to_dart/ this will auto generate your model

if you want the id to be in the result use
final jsonMap = jsonDecode(valueFromApi);
final questions = (jsonMap['questions'] as Map<String, Map>?)
?.entries
.map<Map>((item) => {"id": item.key, ...item.value});
if you don't need the id use
final jsonMap = jsonDecode(valueFromApi);
final questions = (jsonMap['questions'] as Map<String, Map>?)
?.entries
.map<Map>((item) => item.value);
you should also have a Question class has all the attribute you need
and use this line to convert your data to object
final entity = questions?.map((e) => Question.fromJson(e)).toList();

Related

How to retrieve array inside an array into a table using vue js

i want to retrieve some array inside an array but i dont know how, please read my explanation first
here is my json response
{
"Value": [
{
"id": "5ff97d740e788778dd66ee25",
"id_order": "ORD-434183",
"nama_pelanggan": "Herman",
"total": 80000.0,
"jumlah_item": 4.0,
"cart": [
{
"id_cart": "CART-112010",
"nama_produk": "Ayam Bakar",
"jumlah": 4.0,
"harga": 20000.0,
"subtotal": 80000.0,
"notes": "ga ada"
}
],
"admin_no": "ADM-431525",
"admin_name": "Admin",
"created_at": "2021-01-09 16:55:00",
"updated_at": "2021-01-09 16:55:00"
}
],
"Status": true,
"Messages": [
{
"Type": 200,
"Title": "TotalRows",
"Message": "1"
}
]}
as you can see the value of "value" is an array and in that array also have an array "cart"
i want to retrieve this array "cart" and put it in a table
here is how i retrieve the response using vue js Mapping an Array to Elements with v-for
var vm = new Vue({
el: '#app',
data: {
list: {
items: [],
},
}
var formData = new FormData();
formData.append('filterparams', JSON.stringify(filters));
formData.append('display', JSON.stringify(_self.list.config.display));
formData.append('auth', sessionStorage.getItem("token"));
_self.$http.post(hostapi + 'order/GetByParamsHistory', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
var obj = response.data;
_self.list.items = obj.Value; // the value from array "Value"
here is the table html code
and now I don't know how to insert an existing array in the array into the html table
You can access the array on the basis of the array index.
Suppose, if list contains the json response's value field then you can access it like.
list['0'].cart.

How to fetch data from Dictionary<string, dynamic> (Json DeserializeObject)

I have Deserialized dynamic Json using Newtonsoft. The JSON is complex and dynamic.
{
"last_updated": " ",
"regions": {
"antarctica": {
"name": "Antarctica",
"totals": [],
"list": [
"aq",
"bv",
"gs",
"tf",
"hm"
]
},
"world": {
"name" : "",
"totals": {
"confirmed": 250566,
"daily_confirmed": 0,
"recovered": 202098,
"deaths": 35205,
"daily_deaths": 0,
"critical": 676,
"tests": 7249844
},
"list": [
{
"country": "Italy",
"country_code": "it",
"state": "Lombardy",
"confirmed": 85775,
"deaths": 15662,
"critical": 231,
"recovered": 231,
"tests": 43442,
"daily_confirmed": -1,
"daily_deaths": -1
}, and so on ..
To overcome the data type issue I have used the dynamic objects
[JsonTypedExtensionData]
public Dictionary<string, dynamic> items { get; set; }
Up to This works well. Now I am trying to fetch the data out of this dynamic Dictionary
var report = await GetCountryReport();
Dictionary<string, dynamic> Dict = report.regions.results["world"].items;
I'm getting data as Dict Count (2)
[0] = {[list, {[ {"country": "Italy","confirmed": 4149,"deaths": 55,"recovered": 2916,"Incidence_Rate": "54.408517127144925","Case-Fatality_Ratio": "1.274822260357931","last_updated": "2020-08-10T22:30:32Z","...
[1] = {[totals, {{"confirmed": 20218306,"recovered": 12814226,"deaths": 737481,"critical": 64743,"tests": 370260493}}]}
How do I fetch the values of each element from the Dictionary like "values.list.country" etc..?
Visual Studio debug - output
You can do it like below:
var list = Dict.Where(x => x.Key == "list").Select(x => x.Value).SingleOrDefault();
var data = ((JArray)list).Select(x => new
{
country = (string)x["country"],
state = (string)x["state"],
confirmed = (int)x["confirmed"]
//...other properties in list
}).ToList();
The data structure is like below:
Then, you can use a foreach loop to get the specify value:
foreach(var x in data)
{
var country = x.country;
var state = x.state;
var confirmed = x.confirmed;
}

How to parse Json array object?

I am trying to parse a Json file in Qt application but i am stuck at a point.
I have a json file which contains arrays with properties. Now i have a Category class which has a items as member variable. Now i would like to parse the properties and create a unique category object and under this object i would like to add the properties.
I have achieved this by hardcoding:
auto vehicle = std::make_unique<Item>("Coordinates");
vehicle->addEntry(std::make_unique<PropertyItem>("TODO", "x", PropertyType::FLOAT, false, *vehicle.get()));
categories.emplace_back(std::move(vehicle));
void Model::loadItemsFromJson() {
// Vehicle
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json");
QJsonArray properties = obj["properties"].toArray();
/// No idea here how to achive
}
Should i change the Json for better handling or could this be achieved easily?
Thank you
--------------------------EDIT---------------------
Now my json looks like this:
{
"General": [{
"Address": "TODO",
"Readonly": false
},
],
"Coordinates": [{
"Address": "TODO",
"Readonly": false
}
]
]
}
and my implementation:
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json");
QVariantMap map = obj.toVariantMap();
for (auto& m : map.keys()) {
// How to create objects??
}
If you structure your JSON like your objects, e.g.
{
"Categories" : {
"General" : [{
"Address" : "TODO",
"Name" : "Name",
"Type" : "string",
"ReadOnly" : "true"
}, ...],
"World Coordinates" : [...]
}
Then you just parse out each CategoryItem and ScenarioPropertyItem
PropertyType toPropertyType(QJsonValue value); // forward declare
void ScenarioPropertiesModel::loadItemsFromJson() {
// Vehicle
QJsonObject obj = loadJsonFile(":/jsonfiles/vehicle.json")["Categories"].toObject();
for (auto & cat : obj)
{
auto category = std::make_unique<CategoryItem>(cat.name());
for (auto & prop : cat.value().toArray())
{
auto address = prop["Address"].toString();
auto name = prop["Name"].toString();
auto type = toPropertyType(prop["Type"]);
auto readonly = prop["Readonly"].toBool();
category->addEntry(std::make_unique<ScenarioPropertyItem>(address, name, type, readonly));
}
categories.emplace_back(std::move(category));
}
}
PropertyType toPropertyType(QJsonValue value)
{
static std::map<QString, PropertyType> propertyTypes =
{
{ "float", PropertyType::FLOAT },
{ "string", PropertyType::String },
// etc
}
return propertyTypes[value.toString()];
}

How to get json data into apex salesforce?

I have a json like this, which i am getting in the response from http call
{
"offset": 0,
"limit": 50,
"objects": [
{
"id": "59118fb6e4b0168ec4b56692",
"modifiedDate": 1494323126886,
"requestedIds": null,
"mergedIds": [],
"properties": {
"name": [
{
"value": "Abhimanyu",
"metadata": {}
}
],
"company": [],
"title": [],
"email": [
{
"value": "absinghrathore127#gmail.com",
"metadata": {}
}
]
},
"state": "ACTIVE"
},
{
"id": "590d5813e4b03a8336fa1642",
"modifiedDate": 1494046739619,
"requestedIds": null,
"mergedIds": [],
"properties": {
"name": [
{
"value": "Tim Archer",
"metadata": {}
}
],
"company": [],
"title": [],
"email": [
{
"value": "tim#avocado.com",
"metadata": {}
}
]
},
"state": "ACTIVE"
}
],
"size": 2
}
and i am able to get objects from json via this following code :
String s = res.getBody();
Map<String,Object> jsonMap = (Map<String, Object>)JSON.deserializeUntyped(s);
String jsonSubset = JSON.serialize(jsonMap.get('objects'));
What i need is the value of name and email in some variable.
Please help me out in this!!
This is going to be a tedious task but once you've classified your all data into appropriate Wrapper classes then it's fairly simple and easy to maintain.
First thing is to define your MainWrapper class. This will contain all the at it's own level. If it has any Object as key-pair then we need to make sure to include it as a List<>. So This is how your MainWrapper should be:
public class MainWrapper {
Integer offset; // Singleton variable
Integer limits; // Singleton variable
List<ObjectsWrapper> objects; // Collection variable since it starts with [],
Integer size; // Singleton variable
}
Since you've array of objects in JSON that's why I've included it as a List in MainWrapper. Now it's time to define ObjectsWrapper. Below is wrapper defined for the same.
public class ObjectsWrapper {
String id;
String modifieddate;
String requestedIds;
PropertyWrapper properties;
}
Since there is only on properties associated with objects that's why it's a non-collection type. Below is representation of properties.
public class PropertyWrapper {
List<NameWrapper> name;
List<String> company;
List<String> title;
List<EmailWrapper> email;
String state;
}
public class NameWrapper {
String name;
String metadata;
}
I guess now you've a fair idea of how to organize data of JSON into various wrapper class. Once you're done with this, simply deserialize the JSON into MainWrapper class and access it.
For example:
MainWrapper mainJSONWrapper = (MainWrapper) JSON.deserialize(JSON,MainWrapper.class);
List<ObjectsWrapper> objectsLst = mainJSONWrapper.objects;
for(ObjectsWrapper obj:objectsLst) {
List<NameWrapper> lstNameWrapper = obj.properties;
for(NameWrapper nameObj:NameWrapper) {
System.debug('Name:'+nameObj.name);
System.debug('metadata:'+nameObj.metadata);
}
}
Above code is not tested but yes, it will give idea how you should deserialize JSON in appropriate manner.
Also go through this answer..How to deserialize a JSON String to Apex

Get _id from MongoDB using Scala

For a given JSON how do I get the _id to use it as an id for inserting in another JSON?
Tried to get the ID as shown below but does not return correct results.
private def getModelRunId(): List[String] = {
val resultsCursor: List[DBObject] =
modelRunResultsCollection.find(MongoDBObject.empty, MongoDBObject(FIELD_ID -> 1)).toList
println("resultsCursor >>>>>>>>>>>>>>>>>> " + resultsCursor)
resultsCursor.map(x => (Json.parse(x.toString()) \ FIELD_ID).asOpt[String]).flatten
}
{
"_id": ObjectId("5269723bd516ec3a69f3639e"),
"modelRunId": ObjectId("5269723ad516ec3a69f3639d"),
"results": [
{
"ClaimId": "526971f5b5b8b9148404623a",
"pricingResult": {
"TxId": 0,
"ClaimId": "Large_Batch_1",
"Errors": [
],
"Disposition": [
{
"GroupId": 1,
"PriceAmt": 20,
"Status": "Priced Successfully",
"ReasonCode": 0,
"Reason": "RmbModel(PAM_DC_1):ProgramNode(Validation CPG):ServiceGroupNode(Medical Services):RmbTerm(RT)",
"PricingMethodologyId": 2,
"Lines": [
{
"Id": 1
}
]
}
]
}
},
If you want to find objectId's:
import com.mongodb.casbah.Imports._
collection.find(MongoDBObject(/*query*/)).map(_._id)
If you want to query by id:
collection.findOneByID(/*id*/)
I suppose you are using Casbah, the official Driver for Scala.
You just need to modify the map function :
resultsCursor.map { x => x.as[org.bson.types.ObjectId](FIELD_ID)}
Casbah does the deserialization from BSON to Scala object, so you don't have to do it yourself !