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);
}
Related
If response coming from my API is in JSON format then it works fine but if in non-json format then the function does not work. Here is what I am doing -
In my page.ts
import { ApiconnectService } from '../../apiconnect.service';
export class BinaryGraphPage implements OnInit {
value : any;
constructor(
private cs: ApiconnectService
) { }
userGraph(){
this.cs.unilevelGraph().subscribe(response =>{
this.value = response;
})
}
}
In apiconnect.service.ts
unilevelGraph(){
return this.http.get(this.url+'?sponser='+uid);
}
The response coming from API is not in JSON format (I tried JSON format and it works fine but for some reason my response need to be in text/string).
In API, response is a long text and contains html tags such as br tag, span and li tag e.g.: Howdy user, this is your graph list 1.item, 2. item, 3.item, etc.
Since response is not in JSON format, so this errors appear in my console. Error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://......
Can you please suggest me how to rewrite the function userGraph() so that it can work with string or text.
Since you are not getting a JSON response, specify the response type in the options. So, the service method becomes:
unilevelGraph(){
return this.http.get((this.url+'?sponser='+uid), { responseType: 'text' });
}
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/
I managed to load the data from a Json File which is local on my Flutter Project. I also was able to fetch Data from the Internet, if the API Url was like:
https://[API-Server][parameter1:xy][parameter2:abc][API-KEY:lasgoewrijeowfjsdfdfiia]
I archieved that with this code sample:
Future<String> _loadStringFixtures() async {
return await rootBundle.loadString('assets/fixtures.json');
}
Future loadFixtures() async {
String jsonString = await _loadStringFixtures();
final jsonResponse = json.decode(jsonString);
FixturesAPI value = new FixturesAPI.fromJson(jsonResponse);
return value;
}
So far so good...
But now I am facing a problem with the API Provider RapidAPI
You can find the documentation etc. here:
https://rapidapi.com/api-sports/api/api-football/endpoints
As you can see they give some code snippets to connect to their API.
There are some for C, C#, Java, Python etc. You can look into all of them with the link above.
Sadly there is no example for Flutter.
And I do not see a way to adapt these examples.
Normally you can paste your API Key directly into the URL, but this seems not possible here? Or maybe it is?
Does Flutter also have other possibilities to receive data from an API besides the one I did?
Thank you so much in advance for your help!
It's possible to with http package and very easy. You can see in this example below...
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class APIService {
// API key
static const _api_key = <YOU-API-KEY-HERE>;
// Base API url
static const String _baseUrl = "api-football-beta.p.rapidapi.com";
// Base headers for Response url
static const Map<String, String> _headers = {
"content-type": "application/json",
"x-rapidapi-host": "api-football-beta.p.rapidapi.com",
"x-rapidapi-key": _api_key,
};
// Base API request to get response
Future<dynamic> get({
#required String endpoint,
#required Map<String, String> query,
}) async {
Uri uri = Uri.https(_baseUrl, endpoint, query);
final response = await http.get(uri, headers: _headers);
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
return json.decode(response.body);
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load json data');
}
}
}
Then get you request:
//....
APIService apiService = APIService();
// You future
Future future;
//in the initState() or use it how you want...
future = apiService.get(endpoint:'/fixtures', query:{"live": "all"});
//....
Yes it possible in flutter. Use the Dio Package in flutter which is a powerful Http client. Using dio you can set interceptors to add api key to url so you don't have to append it in every request. Setting interceptors will help you.
I want to get JSON data from GoogleSignInAccount.
_googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) async {
if (account != null) {
auth = Auth.fromJson(json.decode(account.toString()));
_signInView.onGoogleResponse(auth);
} else {
_signInView.onGoogleResponse(null);
}
});
but
account.toString() returned the response =>
{
displayName: Mert TUTSAK,
email: merttutsak#gmail.com
}
I want to return the JSON object.
{
"displayName": "Mert TUTSAK",
"email": "merttutsak#gmail.com"
}
How to make it?
What you get is just what toString() produces on a Map.
To get a valid JSON string, use json.Encode() or jsonEncode (they are equivalent)
import 'dart:convert';
...
var json = jsonEncode(account);
print(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"]);