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;
}
Related
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();
here i have added the value to the contactList.listChild but the the string list doesn't return all the value to the parent list it only returns the last added value. i know its a simple mistake though i couldn't figure out where am making mistake.
any suggestion would be helpful.
ContactName contactList = new ContactName();
createJson(){
for(int index = 0; index < _contacts.length; index++){
Contact contact = _contacts?.elementAt(index);
List<Item> numbersList = contact.phones.toList();
for(int i = 0; i < numbersList.length; i++ ){
contactList.listChild = [numbersList[i].value];
}
contactList.name = contact.displayName;
lisJson.add(contactList.toJson());
}
var data = {
"data" : lisJson
};
var body = json.encode(data);
print("$body");
}
// here is my model class
class ContactName extends Object {
String name;
List<String> listChild = new List<String>();
Map toJson() => {"name":name, "phone":listChild};
}
this is what am getting from this
{
"data": [
{
"name": "user1",
"phone": [
"8221551458"
]
},
{
"name": "user2",
"phone": [
"1234567890"
]
}
]
}
// and the output should be something like this
{
"data": [
{
"name": "user1",
"phone": [
"8221551458"
]
},
{
"name": "user2",
"phone": [
"8220780548"
"1234567890"
]
}
]
}
You need to replace
contactList.listChild = [numbersList[i].value]
by
contactList.listChild.add(numbersList[i].value)
Your code is creating a new list on every iteration of the for statement, that's why the last element is the only one you see.
Be sure to initialize contactList.listChild before using it or will throw an exception when trying to add a new element.
I get an error when I try to save an array that comes from a JSON string. I've tried to use RLMArray with no success.
The error I receive is:
'RLMException', reason: 'Property 'page' is of type 'RLMArray<(null)>' which is not a supported RLMArray object type.
My model class:
public class Project: Object, Mappable {
dynamic var id = 0
dynamic var user: User!
dynamic var page: RLMArray!
dynamic var error_message: String! = ""
dynamic var status: String! = ""
override public static func primaryKey() -> String? {
return "id"
}
required convenience public init?(_ map: Map) {
self.init()
mapping(map)
}
public func mapping(map: Map) {
user <- map["user"]
page <- map["page"]
error_message <- map["error_message"]
status <- map["status"]
}
}
JSON File:
let parameters = [
"user": [
"username": "Marcus",
"password": "123asd"
],
"page": [
"home": [
[
"kind": "navigation",
"title": "suite",
"image": "ic_suite",
"backgroundImage": "ic_background1"
],
[
"kind": "navigation",
"title": "jardim",
"image": "ic_jardim",
"backgroundImage": "ic_background2"
]
],
"suite": [
[
"kind": "button",
"title": "My Master Suite",
"textColor": "0x000000",
"textSize": "16"
]
]
],
"status": "success",
"error_message": ""
]
self.project = Mapper<Project>().map(parameters)
Your class inherits from Object, Realm Swift's base class, but is attempting to use RLMArray, a Realm Objective-C type, in its interface. You cannot mix Realm Swift and Realm Objective-C in this manner. You should use List<T> for array properties when using Realm Swift.
In the below JSON I was trying to access the second array in the header.Basically "Node", "Percentage", "Time","File System" needs to captured as I will have to insert into SQL.My code is giving the complete array of header.
JObject jsonObject = JObject.Parse(jsonString);
List<string> childTokens = new List<string>();
foreach (var childToken in jsonObject.Children<JProperty>())
childTokens.Add(childToken.Name);
foreach (string childToken in childTokens)
{
if (jsonObject[childToken] is JObject)
{
JObject jObject = (JObject)jsonObject[childToken];
var jProperty = jObject.Children<JProperty>();
try
{
if (jProperty.LastOrDefault(x => x.Name == "header") != null)
{
foreach (var headerValue in jProperty.LastOrDefault(x => x.Name == "header").Value.Children())
table.Columns.Add("[" + headerValue.ToString() + "]");
table.Columns.Add("[ID]");
table.Columns.Add("[comments]");
}
JSON sample:
"DISK" : {
"alarm_count" : 5,
"column_width" : [
12,
14,
16,
14
],
"header" : [
[
"",
"Max Disk Usage",
3
],
[
"Node",
"Percentage",
"Time",
"File System"
]
] }
I can have number of arrays in header .. don't want to hardcode it.. I should be always be able to pick the last array in header child token..Please advise .. thanks
Assuming your json snippet was valid and is part of an object like:
{
"DISK": {
"alarm_count": 5,
"column_width": [
12,
14,
16,
14
],
"header": [
[
"",
"Max Disk Usage",
3
],
[
"Node",
"Percentage",
"Time",
"File System"
]
]
}
}
You could do this:
JObject obj = ...;
var secondHeader = obj["DISK"]["header"].Last();
Hi I am developing small application in which I am trying to pass some data in http post method. So I want to send my data like this form
"storeid": "151",
"floordata": {
"entry": [
10,
15
],
"exit": [
10,
15
],
"section": [
{
"id": "0",
"sectionname": "ABC",
"category": "office",
"boundary": [
[
85,
258
],
[
85,
298
],
[
125,
298
],
[
125,
258
],
[
85,
258
]
"description": "Mobile based company"
}
]
},
"category": null,
"description": null
so my problem is regarding section parameter. I am doing this for section parameter.
String section = "section=";
// Problem for me is here ...
JSONArray sections = new JSONArray();
List<List<Float>> sectionCords = new ArrayList<List<Float>>();
List<Float> sectionCordData = new ArrayList<Float>();
sectionCordData.add(0.0f);
sectionCordData.add(0.1f);
List<Float> sectionCordData1 = new ArrayList<Float>();
sectionCordData1.add(0.0f);
sectionCordData1.add(0.1f);
sectionCords.add(sectionCordData);
sectionCords.add(sectionCordData1);
JSONObject sectionObj = new JSONObject();
//List<JSONObject> cordList = new ArrayList<JSONObject>();
try {
sectionObj.put("category", "office");
sectionObj.put("description", "Mobile based company");
sectionObj.put("sectionname", "mobiotics");
sectionObj.put("id", 0);
sectionObj.put("boundary", sectionCords); // Check Here i am sending as list ...
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sections.put(sectionObj);
section += sections;
section +="&";
But In actual it my section boundary parameter going as string instead of list. Like this
boundary=[
[
0.0,
0.1
],
[
0.0,
0.1
]
],storeid=156&floor=2§ion=[
{
"id": 0,
"sectionname": "mobiotics",
"category": "office",
"boundary": "[[0.0, 0.1], [0.0, 0.1]]", // See here is my problem ...
"description": "Mobile based company"
}
],entry=[
10,
15
],exit=[
10,
15
]
How to send it as list instead of string. Need Help. Thank you.
Define sectionChords, and sectionCordData* as JSONArray instead of List:
JSONArray sectionChords = new JSONArray();
JSONArray sectionCordData = new JSONArray();
sectionCordData.put(0.0f);
sectionCordData.put(0.1f);
JSONArray sectionCordData1 = new JSONArray();
sectionCordData1.put(0.0f);
sectionCordData1.put(0.1f);
sectionCords.put(sectionCordData);
sectionCords.put(sectionCordData1);
It must do what you want according to docs.
Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection.
But it puts JSON representation of your object as String. So you should use either JSONArrays or Java objects. You should not mix them.
controller :
public JsonResult Index()
{
List<Location> location = (from a in db.Locations select a).ToList();
return Json(location, JsonRequestBehavior.AllowGet);
}