how to convert json response to c# dictionary? - json2csharp

I have the following json response and I want to convert it into C# model.
I am facing the issue that it has key value as integer and when I'm converting it into C# through converter it is making as many classes as these values. how to convert it as dictionary while deserialization.
"data": {
"564448665437833501": {
"city_name": "Mount Cook",
"country_name": "New Zealand",
"country_code": "NZ"
},
"5862745215379501543": {
"city_name": "Coolangatta",
"country_name": "Australia",
"country_code": "AU"
},
}

Related

How do I use/store the value of a JSON response? [duplicate]

This question already has an answer here:
How can I access and process nested objects and arrays?
21 answers
I'd like to determine what country a visitor of my website is from based off of their geoIP so I can determine whether that visitor is visiting their country-specific website or not and prompt them with a confirmation popup asking if they'd like to be redirected in the event that they're not. However, my JavaScript knowledge is limited/minimal. How would I store/use and return a specific value to be used dynamically from a JSON response?
For example, I'd like to use the following country iso code "US".
"country": {
"iso_code": "US",
Using MaxMind's GeoIP2 JavaScript Client API with the following JavaScript:
<script type="text/javascript" src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js"></script>
<script type="text/javascript">
var onSuccess = function(location){
console.log(
"Lookup successful:\n\n"
+ JSON.stringify(location, undefined, 4)
);
};
var onError = function(error){
console.log(
"Error:\n\n"
+ JSON.stringify(error, undefined, 4)
);
};
geoip2.city(onSuccess, onError);
</script>
This JSON returned looks like this:
{
"city": {
"geoname_id": 5368361,
"names": {
"es": "Los Ángeles",
"fr": "Los Angeles",
"ja": "ロサンゼルス",
"pt-BR": "Los Angeles",
"ru": "Лос-Анджелес",
"zh-CN": "洛杉矶",
"de": "Los Angeles",
"en": "Los Angeles"
}
},
"continent": {
"code": "NA",
"geoname_id": 6255149,
"names": {
"fr": "Amérique du Nord",
"ja": "北アメリカ",
"pt-BR": "América do Norte",
"ru": "Северная Америка",
"zh-CN": "北美洲",
"de": "Nordamerika",
"en": "North America",
"es": "Norteamérica"
}
},
"country": {
"iso_code": "US",
"geoname_id": 6252001,
"names": {
"ru": "США",
"zh-CN": "美国",
"de": "USA",
"en": "United States",
"es": "Estados Unidos",
"fr": "États-Unis",
"ja": "アメリカ合衆国",
"pt-BR": "Estados Unidos"
}
},
"location": {
"accuracy_radius": 50,
"latitude": 34.0669,
"longitude": -118.3109,
"metro_code": 803,
"time_zone": "America/Los_Angeles"
},
"postal": {
"code": "90020"
},
"registered_country": {
"iso_code": "US",
"geoname_id": 6252001,
"names": {
"ja": "アメリカ合衆国",
"pt-BR": "Estados Unidos",
"ru": "США",
"zh-CN": "美国",
"de": "USA",
"en": "United States",
"es": "Estados Unidos",
"fr": "États-Unis"
}
},
"subdivisions": [
{
"iso_code": "CA",
"geoname_id": 5332921,
"names": {
"zh-CN": "加利福尼亚州",
"de": "Kalifornien",
"en": "California",
"es": "California",
"fr": "Californie",
"ja": "カリフォルニア州",
"pt-BR": "Califórnia",
"ru": "Калифорния"
}
}
],
"traits": {
"autonomous_system_number": 7018,
"autonomous_system_organization": "AT&T Services, Inc.",
"isp": "AT&T Services",
"organization": "AT&T Internet Services",
"ip_address": "12.125.142.34"
},
"represented_country": {
"names": {}
}
}
GeoIP2 JavaScript Tutorial
Thanks in advance.
You already have a Json, then you could do something like this:
var onSuccess = function(location){
console.log(location.country.iso_code);
};
In addiction to Emeeus answer, if you want to save locally the response in order to not repeat the request to server or ask user twice the same question, you may use window.localStorage object. This object will persist data in the user browser even when user closes the browser, and data will be available for your domain. If you want to store just while user is browsing your site in that moment, and clear on close, use sessionStorage.
You should always pass a string to a field of localStorage. Your code would be something like:
var geoData;
var onSuccess = function(location){
window.localStorage.geoData = JSON.stringify(location);
// ... do whatever you want with location ...
};
// ... on error ...
if (! window.localStorage.geoData)
geoip2.city(onSuccess, onError);
else
onSuccess(JSON.parse(window.localStorage.geoData));
Remember that JSON.parse can throw an error if the JSON is not valid. I recommend you to surround the code with a try {...} catch (e) {geoip2.city(onSuccess, onError)}, as if the parse fails, it the catch will be executed and can request the server for data normally.

Accessing json data from wunderground API?

I have this async function below that taps into a weather API and I would just like to retrieve two pieces of info from the API: Temperature in F & C. I removed the API_Key but it's free to get one on the site if necessary.
I can confirm I am receiving the json object due to my console.log(response) statement, but Im not sure how to access these data points in such heavily embedded json notation.
I guess my question is if I wanted to access say 'full' for full city name I thought I'd do something like response.observation_location.full but that doesn't work...
Help?
async loadWeather() {
// let zip = this.args.zip || 97239;
let response = await fetch(`http://api.wunderground.com/api/API_KEY/conditions/q/CA/San_Francisco.json`);
console.log(response);
this.weather = await response.json();
// setTimeout( () => { this.loadWeather(); }, 2000);
}
Here is a partial output of the response json:
{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
},
"current_observation": {
"image": {
"url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
"title": "Weather Underground",
"link": "http://www.wunderground.com"
},
"display_location": {
"full": "San Francisco, CA",
"city": "San Francisco",
"state": "CA",
"state_name": "California",
"country": "US",
"country_iso3166": "US",
"zip": "94102",
"magic": "1",
"wmo": "99999",
"latitude": "37.77999878",
"longitude": "-122.41999817",
"elevation": "60.0"
},
"observation_location": {
"full": "SOMA, San Francisco, California",
"city": "SOMA, San Francisco",
"state": "California",
"country": "US",
"country_iso3166": "US",
"latitude": "37.778488",
"longitude": "-122.408005",
"elevation": "23 ft"
},
I have tried doing console.log(response["current_observation"]) just to access a nested data value but that doesnt seem to work as it returns undefined.
Ok I solved my own issue, but for the record:
response needed to be converted to json via resonse.json()
and then I can access properties as expected
this.weather = await response.json();
console.log(this.weather["current_observation"]["temp_f"]);
console.log(this.weather["current_observation"]["temp_c"]);

AngularJs extracting values from JSON Object and attaching to $scope

I am receiving the following JSON data object
{
"ip": "**Removed**",
"country_code": "GB",
"country_name": "United Kingdom",
"region_code": "ENG",
"region_name": "England",
"city": "Plymouth",
"zip_code": "PL6",
"time_zone": "Europe/London",
"latitude": 50.442,
"longitude": -4.0828,
"metro_code": 0
}
How do I extract the first two values and attach them to the $scope so that they can be shown in the template when received.?
Assuming that you're getting it via http request your call would be like this:
$http.get("./getData.php").success(function(data) {
$scope.data = {};
$scope.data["ip"] = data["ip"];
$scope.data["country_code"] = data["country_code"];
}
You can set this whole object to a property on the scope in your controller:
$scope.jsonObject = jsonObject;
Then in your template, just access it like:
<span>{{jsonObject.country_code}}</span>
If I understood correctly, first store that JSON into one varaible
Var jsonData = {
"ip": "Removed",
"country_code": "GB",
"country_name": "United Kingdom",
"region_code": "ENG",
"region_name": "England",
"city": "Plymouth",
"zip_code": "PL6",
"time_zone": "Europe/London",
"latitude": 50.442,
"longitude": -4.0828,
"metro_code": 0
}
$scope.firstTwoValues = jsonData.ip+jsonData.country_cody;
For dynamic names u can use smth like this:
someDataService.get()
.then(function(res) {
var keys = Object.keys(res.data).splice(1,2);
angular.forEach(keys, function(key){
$scope[key] = res.data[key];
});
return $q.when();
}

Ember.js REST Adapter use JSON root(use ember-data)

The Ember.js REST Adapter expects the JSON to be returned as:
{
"customer": {
"CustomerID": "ALFKI",
"CompanyName": "Alfreds Futterkiste",
"ContactName": "Maria Anders",
"ContactTitle": "Sales Representative",
"id": "b0d16ed0-c901-4ca3-ba41-7fc74c96909f"
}
}
But my API returns the data without a root element:
{
"CustomerID": "ALFKI",
"CompanyName": "Alfreds Futterkiste",
"ContactName": "Maria Anders",
"ContactTitle": "Sales Representative",
"id": "b0d16ed0-c901-4ca3-ba41-7fc74c96909f"
}
I find a question here: Ember.js REST Adapter without JSON root, but the answers is too old, don't works
in the newest version of ember and ember-data.
Sorry for my poor English, hope that's clear...
Override serializeIntoHash in the serializer:
serializeIntoHash: function(data, type, record, options) {
Ember.merge(data, this.serialize(record, options));
}
For your second question, look at typeForRoot. Why not just read the entire page on adapters?

d3 stacked bar chart - data reformat required

JSONData = [
{ "Region": "NA", "Engagment": "Full"},
{ "Region": "NA", "Engagment": "Partial"},
{ "Region": "NA", "Engagment": "Full"},
{ "Region": "NA", "Engagment": "Partial"},
{ "Region": "LA", "Engagment": "Full"},
{ "Region": "LA", "Engagment": "Partial"},
{ "Region": "LA", "Engagment": "Full"},
{ "Region": "LA", "Engagment": "Partial"}
]
I'd like to use the above data set to build out a d3 stacked bar chart based using the Regions as labels and then total the Engagement values based on the sum of their unique values. I was able to use the _groupBy method in underderscore.js to group the regions but am stuck trying to format the data so that it looks like:
Region Full Partial
NA 2 2
LA 2 2
I'm testing the code in the following jsfiddle library. http://jsfiddle.net/jkeohan/kvg9g5z7/
Any suggestions of reformatting the data to provide d3 numerical values instead of text?
Much appreciated..

Resources