Finding a String from JSON in Dart - json

I really need to find some information inside a JSON file, in Java I can easily find a string from a JSON Object with
JSON_Object.getString("String Here");
But I cannot find anything similar in Dart. So far all I can see is:
var jsonobject = new JsonObject.fromJsonString(jsonString);
print(jsonobject.something);
but the problem with this is that I cannot find a String nested in other bits of JSON. Here is the JSON I am using:
http://maps.google.com/maps/api/geocode/json?latlng=51.4346502,-0.1020349
Thanks,
Luca

this is some code that does the trick. You might have to change it a little bit to fit your needs:
import 'package:http/http.dart';
import 'dart:convert';
void main() {
get('http://maps.google.com/maps/api/geocode/json?latlng=51.4346502,-0.1020349').then((Response response) {
var json = JSON.decode(response.body);
json['results'].forEach((result){
print(result['formatted_address']);
});
});
}

If you know the structure of your JSON you can access it directly
var json = ...
print(json["results"][0]["formatted_address"]);

Related

Flutter API throwing Exception

I was practicing this covid-19 tracker application using flutter from a tutorial on YouTube, so after writing a few code when I hit the API and run the application, it throws this exception, I don't understand why as I am a beginner and a newbie on Flutter.
import 'dart:convert';
import 'package:covid_tracker/Model/world_states_model.dart';
import 'package:http/http.dart' as http;
import 'Utilities/app_url.dart';
class StatesServices {
// async means waiting for your request
Future<WorldStatesModel> fetchWorldStatesRecords() async {
final response = await http.get(Uri.parse(AppUrl.worldStatesApi));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
return WorldStatesModel.fromJson(data);
} else {
throw Exception('Error');
}
}
}
class AppUrl {
// this is our base url
static const String baseUrl = 'https://disease.sh/v3/covid-19';
// fetch world covid states
static const String worldStatesApi = '${baseUrl}all';
static const String countriesList = '${baseUrl}countries';
}
You are getting a status code that's not 200. Therefore your application throws an error, just as you have programmed it!
The first step would be to actually figure out why you are getting a different status code from 200. Looking at your code it seems that you try to visit '${baseUrl}all'. This translates to https://disease.sh/v3/covid-19all. This URL however does not exist.
To fix your issue try adding a / after ${baseUrl}. Such that it becomes '${baseUrl}/all'. Or add the change the baseUrl variable to https://disease.sh/v3/covid-19/. After that, your error should be resolved.
I recommend printing to the console what links you are trying to load. It would probably prevent this kind of issue in the future. Or even more useful, include it in the exception you throw. :)
if stataus !=200 from API,
You are throwing exception in this line
throw Exception('Error');
it shows API is not returning the needed data.
Try to change line
static const String baseUrl = 'https://disease.sh/v3/covid-19';
to
static const String baseUrl = 'https://disease.sh/v3/covid-19/';

how to read JSON with HTML in Flutter App?

Fetching JSON in Flutter App, which contains Nested Json and HTML content is not working.
Example:
{"off":
{
"02":{
"id":"02"
},
"name":"022",
"type":"Test",
"phn":[1,2,3,4],
"org":"wann",
"email":"cc#gmail.com",
"description":"AS",
"html":"<div>ID: 02<br>Name: 022<br>Org: wann<br>Description: AS</div>"
}
}
####################
final jsonResponse= json.decode(response.body);
Error:
Half content of JSON fetches from API due to HTML.
Hm... When I tested to convert from string to Json, it looks good.
Because the data you attached is Map type, I tested with all string.
import 'dart:convert' show json;
import 'dart:core';
void main() {
var data ='''{"off":
{
"02":{
"id":"02"
},
"name":"022",
"type":"Test",
"phn":[1,2,3,4],
"org":"wann",
"email":"cc#gmail.com",
"description":"AS",
"html":"<div>ID: 02<br>Name: 022<br>Org: wann<br>Description: AS</div>"
}
}''';
final jsonResponse= json.decode(data);
print(jsonResponse);
}

typescript/angular: can't iterate over Map parsed from json

I'm new to both typescript and angular (coming from quite solid Java/kotlin background).
Wrote a class:
export interface GeoData {
allregions: Map<string, string>;
}
to parse this json:
{"allregions":{"whatever":"WHT","a region":"ARE","something":"SMT"}
The json is correctly read from a file using HttpClient.get() and I can see the correct content in the variable using debug. also, this code:
console.log(data.allregions["whatever"])
correctly prints WHT.
unfortunately, this:
data.allregions.forEach((value: string, key: string) => {
console.log(key, value);
});
throws data.allregions.forEach is not a function
also this:
console.log(data.allregions.size)
prints undefined
and this:
console.log(data.allregions.entries.lenght)
throws data.allregions.entries is undefined
what is going on here?
I see you are applying forEach on a object. Combine Object.keys() and forEach()
var data = {"allregions":{"whatever":"WHT","a region":"ARE","something":"SMT"}}
Object.keys(data.allregions).forEach(function(key) {
console.log(`key: ${key}, value:${data.allregions[key]}`);
});

How does Fetching | Loading json Data to a List<myClass> in Flutter Exactly work?

How does that works in my case down below?
I tried many ways but i just could not figure it out.
Also, How to load a local json file and use it's keys:values as a class?
class Countries{
int id;
String name;
Countries(this.id,this.name);
static Future<List<Countries>> getJsonCountries() async {
String apiUrl = "https://gist.githubusercontent.com/keeguon/2310008/raw/bdc2ce1c1e3f28f9cab5b4393c7549f38361be4e/countries.json";
http.Response resp = await http.get(apiUrl);
return json.decode(resp.body);
}
static List<Countries> getCountries() {
List<Countries> ls = getJsonCountries() as List<Countries>; // Idk why this does not work ..
return ls;
// return <Countries>[ <-- this works fine ...
// Countries(1,'Morocco'),
// Countries(2,'France'),
// Countries(3,'USA'),
// Countries(4,'Tunisia'),
// ];
}
}
Your json file is not properly formatted. Strings should be wrapped in double quotes. This will immediately stop you from parsing the json in Dart/Flutter. Both the values and the keys need to be in double quotes to be parsed by Dart.
You can check it yourself by copy pasting your json in here and testing it: https://jsonformatter.curiousconcept.com/

Angular HttpClient returns string data instead of parsed JSON

I've been in the process of migrating a code base from Angular 4.x to 5.x, and I'm running into a strange issue. I have a service function, that is intended to return a list of objects to the front end, which I then massage into a specific data format. I know I'll need to keep the mapping, but I'm a little miffed that it's returning just plain string data.
The original function is this: (using Http from #angular/http just renamed to HttpClient)
public GetVendors(showAll = true, screenArea: number = 0): Observable<Array<SelectModel>> {
let link = AppSettings.API_COMMON_VENDORS;
let params: URLSearchParams = new URLSearchParams();
params.set('showAll', showAll.toString());
params.set('screenArea', screenArea.toString());
let requestOptions = new RequestOptions();
requestOptions.search = params;
return this.httpClient.get(link, requestOptions).map(response => {
let result = JSON.parse(response.json());
let list = new Array<SelectModel>();
let vendors: Array<any> = result;
vendors.forEach(vendor => {
list.push(this.CreateSelectModel(vendor));
});
return list;
});
}
and after ripping out ALL of the Http code, here's the function again using HttpClient from #angular/common/http
public GetVendors(showAll = true, screenArea: number = 0): Observable<Array<SelectModel>> {
let link = AppSettings.API_COMMON_VENDORS;
let params: HttpParams = new HttpParams()
.set('showAll', showAll.toString())
.set('screenArea', screenArea.toString());
return this.httpClient.get<Array<any>>(link, {params}).map(response => {
let list = new Array<SelectModel>();
response.forEach(vendor => {
list.push(this.CreateSelectModel(vendor));
});
return list;
});
}
The issue with this is it kind of defeats the purpose of the new client parsing json for me. The response object is a string representing the JSON of the data I requested, but it's still in a string form, and not the type defined in the get<>() call.
What am I doing wrong here? shouldn't it be parsed already?
Sample Response Data A'la Network Tools in Chrome Dev Tools:
Sample Response Body:
Dev Tools Screenshot with Value of response
The backend (C#) responds with this:
[HttpGet]
public JsonResult Vendors(bool showAll = false, int screenArea = 0)
{
var vendors = _commonBL.GetVendorsSlimForUser(UserModel, UserModel.CustomerId, showAll, screenArea);
return GetJson(vendors);
}
this is how it worked before the Http => HttpClient migration, and it worked with ONE JSON.parse() The data in the return line is simply a standard List<T>
This is what the raw response for your data should look like:
[{"Id":1234,"Name":"Chris Rutherford"}]
But this is what it actually looks like:
"[{\"Id\":1234,\"Name\":\"Chris Rutherford\"}]"
So somewhere in your server code, you have applied JSON encoding twice. Once you correct that, HttpClient will do the right thing.
I'd quote an answer from this thread. Hope it will shed some light on how things work, read it thoroughly it enlightened me tough its not easy to find.
TypeScript only verifies the object interface at compile time. Any object that the code fetches at runtime cannot be verified by
TypeScript.
If this is the case, then things like HttpClient.Get should not
return Observable of type T. It should return Observable of type Object because
that's what is actually returned. Trying to state that it returns T
when it returns Object is misleading.
In the documentation the client's return section says this:
#return an Observable of the body as
type T.
In reality, the documentation should say:
#return an Observable of the body which
might be T. You do not get T back. If you got T back, it would
actually be T, but it's not.