This is my Json data :
{
"result":"0",
"school_name":"Global Academy International",
"school_code":"GAIS",
"dashboard":"{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":159,\"privilege_desc\":\"V4_MYATTENDANCE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1188},{\"activity_id\":159,\"privilege_desc\":\"V4_MYLEAVESTATUS\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1189},{\"activity_id\":159,\"privilege_desc\":\"V4_MEMO\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1193},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1198},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISELATE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1201},{\"activity_id\":162,\"privilege_desc\":\"V4_LEAVE_REQUISITION\",\"activity_desc\":\"V4_TEACHER_LEAVE\",\"privilege_id\":1203},{\"activity_id\":164,\"privilege_desc\":\"V4_ASSIGNMENT\",\"activity_desc\":\"V4_STUDENT_ASSIGNMENT\",\"privilege_id\":1206},{\"activity_id\":166,\"privilege_desc\":\"V4_SCHOOL_CALENDAR\",\"activity_desc\":\"V4_CALENDAR\",\"privilege_id\":1208},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\",\"profile\":{\"empid\":\"EMP183\",\"name\":\"BACHIR Raji Kashkash\",\"designation\":\"TEACHER\",\"photo_path\":\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\",\"department_name\":\"HIGH SCHOOL - T\"}}",
"employee_id":"EMP183",
"school_url":"http://ict.gaiqatar.com"
}
I want to print only this data from jSON data:
[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}]
How to get this data from whole jSON data ?
Import the following package:
import 'dart:convert';
Decode the json result returned and access the specific field you want:
final body = json.decode(response.dashboard);
print(body['privilege']);
Basically after parsing your initial json you need to parse the nested field as well (privileges) since it's not a valid json object. Usually I would do this from the server and send a proper json response to the client (flutter).
If this can't be done then you just have to parse the json response, walk through it and parse and nested fields as well.
Edit:
Noticed your json wasn't formatted properly this is an example code. You can run this in dartpad
import 'dart:convert';
void main() {
final jsonString = '{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\"}';
final parsedJson = json.decode(jsonString);
final privilege = parsedJson['privilege'];
print(privilege);
}
The problem is your json is not properly formatted. first format it properly, you can copy and paste your json in any prettify json website and try to format it properly, if problem persists then do let me know.
The Json Data
final jsonData = """{
"result":"0",
"school_name":"Global Academy International",
"school_code":"GAIS",
"dashboard":"{\\"privilege\\":[{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYPROFILE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1185},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYTIMETABLE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1186},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYATTENDANCE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1188},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYLEAVESTATUS\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1189},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MEMO\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1193},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1198},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISELATE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1201},{\\"activity_id\\":162,\\"privilege_desc\\":\\"V4_LEAVE_REQUISITION\\",\\"activity_desc\\":\\"V4_TEACHER_LEAVE\\",\\"privilege_id\\":1203},{\\"activity_id\\":164,\\"privilege_desc\\":\\"V4_ASSIGNMENT\\",\\"activity_desc\\":\\"V4_STUDENT_ASSIGNMENT\\",\\"privilege_id\\":1206},{\\"activity_id\\":166,\\"privilege_desc\\":\\"V4_SCHOOL_CALENDAR\\",\\"activity_desc\\":\\"V4_CALENDAR\\",\\"privilege_id\\":1208},{\\"activity_id\\":168,\\"privilege_desc\\":\\"V4_LOGOUT\\",\\"activity_desc\\":\\"V4_LOGOUT\\",\\"privilege_id\\":1210}],\\"resultPrivilege\\":\\"0\\",\\"resultProfile\\":\\"0\\",\\"profile\\":{\\"empid\\":\\"EMP183\\",\\"name\\":\\"BACHIR Raji Kashkash\\",\\"designation\\":\\"TEACHER\\",\\"photo_path\\":\\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\\",\\"department_name\\":\\"HIGH SCHOOL - T\\"}}",
"employee_id":"EMP183",
"school_url":"http://ict.gaiqatar.com"
}""";
Used double \\ to scape correctly the char "...
And then:
final parsedJson = json.decode(jsonData);
print(parsedJson['dashboard']);
If you prefer, you can parse only dashboard section to filter some itens programaticaly...
final dashboardParsed = json.decode(parsedJson['dashboard']);
print(dashboardParsed);
Final result
final jsonData = """{
"result":"0",
"school_name":"Global Academy International",
"school_code":"GAIS",
"dashboard":"{\\"privilege\\":[{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYPROFILE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1185},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYTIMETABLE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1186},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYATTENDANCE\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1188},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MYLEAVESTATUS\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1189},{\\"activity_id\\":159,\\"privilege_desc\\":\\"V4_MEMO\\",\\"activity_desc\\":\\"V4_DASHBOARD\\",\\"privilege_id\\":1193},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1198},{\\"activity_id\\":161,\\"privilege_desc\\":\\"V4_SUBJECTWISELATE\\",\\"activity_desc\\":\\"V4_STUDENT_ATTENDANCE\\",\\"privilege_id\\":1201},{\\"activity_id\\":162,\\"privilege_desc\\":\\"V4_LEAVE_REQUISITION\\",\\"activity_desc\\":\\"V4_TEACHER_LEAVE\\",\\"privilege_id\\":1203},{\\"activity_id\\":164,\\"privilege_desc\\":\\"V4_ASSIGNMENT\\",\\"activity_desc\\":\\"V4_STUDENT_ASSIGNMENT\\",\\"privilege_id\\":1206},{\\"activity_id\\":166,\\"privilege_desc\\":\\"V4_SCHOOL_CALENDAR\\",\\"activity_desc\\":\\"V4_CALENDAR\\",\\"privilege_id\\":1208},{\\"activity_id\\":168,\\"privilege_desc\\":\\"V4_LOGOUT\\",\\"activity_desc\\":\\"V4_LOGOUT\\",\\"privilege_id\\":1210}],\\"resultPrivilege\\":\\"0\\",\\"resultProfile\\":\\"0\\",\\"profile\\":{\\"empid\\":\\"EMP183\\",\\"name\\":\\"BACHIR Raji Kashkash\\",\\"designation\\":\\"TEACHER\\",\\"photo_path\\":\\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\\",\\"department_name\\":\\"HIGH SCHOOL - T\\"}}",
"employee_id":"EMP183",
"school_url":"http://ict.gaiqatar.com"
}""";
final parsedJson = json.decode(jsonData);
print(parsedJson['dashboard']);
final dashboardParsed = json.decode(parsedJson['dashboard']);
print(dashboardParsed);
I Scaped \" because I'm storing the string into a var, if it comes from your web api, should work too.
Related
I am trying to persist a simple List<Map<String,dynamic>> with GetStorage.
The documentation says:
When to use GetStorage:
simple Maps storage.
cache of http requests
storage of simple user information.
simple and persistent state
storage any situation you currently use sharedPreferences.
So, I did not encoded/decoded to json String.
In the end, getting error
type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>?' in type cast
Here is my code, and error is thrown at box.read() method:
final box = GetStorage();
var payments = <Payment>[].obs;
Future<void> savePaymentsToDB() async {
var paymentsAsMap = payments.map((payment) => payment.toJson()).toList();
await box.write('payments', paymentsAsMap);
}
void getPaymentsFromDB() {
var result = box.read<List<Map<String, dynamic>>>('payments');
if (result != null) {
payments =
result.map((payment) => Payment.fromJson(payment)).toList().obs;
}
}
You need to encode paymentsAsMap to json string. The toJson method on your model, only coverts that model to json object (key,value pair). To store that in shared preferences or getStorage you should convert that json object to string.
import 'dart:covert';
// Storing data
...
var paymentsAsMap = payments.map((payment) => payment.toJson()).toList();
String jsonString = jsonEncode(paymentsAsMap);
await box.write('payments', jsonString);
// fetching data
var result = box.read('payments');
dynamic jsonData = jsonDecode(result);
payments = jsonData.map((payment) => Payment.fromJson(payment)).toList().obs;
I was using parse server sdk in my app for database.
I have three class in my Back4App Dashboard which are "_User", "Office", "Office_Members".
In Office_Members class it has following columns,
user_id (Pointer to _User)
office_id (Pointer to Office)
count
To fetch the data including Pointer to _User as well from Office_Members, I am using following code,
QueryBuilder<ParseObject> parseQuery = QueryBuilder<ParseObject>(ParseObject("Office_Members"))
..whereEqualTo("office_id", ParseResponse_OfficeObject)
..includeObject(["user_id "]);
ParseResponse apiResponse = await parseQuery.query();
Output :
Payload : [{"className":"Office_Members","objectId":"twpDY51PUK","createdAt":"2020-08-14T09:58:59.775Z","updatedAt":"2020-08-14T09:58:59.775Z","office_id":{"__type":"Pointer","className":"Office","objectId":"4dkfSMrwBI"},"user_id":{"__type":"Pointer","className":"_User","objectId":"Hx5xJ5ABxG"},"count":1}]
In my payload response i am not getting whole user_id pointer response.
So can anybody help me that what i might be doing wrong?
Thanks.
The data should be included.
The logging function simply does not print the data of pointers.
The data should be included. The print function not print the data of pointers.
You can print it out directly for testing purposes, E.g.
response.results[0].get('user_id').get('name')
Evaluation Expression E.g.
In your model u can access at same way, E.g
Call Model
if(response.success){
return response.results.map((p) => Example.fromParse(p)).toList();
} else {
throw ParseErrors.getDescription(response.error.code);
}
Model
import 'package:parse_server_sdk/parse_server_sdk.dart';
class Example {
Example({this.id, this.name});
Example.fromParse(ParseObject parseObject) :
id = parseObject.objectId,
name = parseObject.get('user_id').get('name');
final String id;
final String name ;
#override
String toString() {
return 'Example{id: $id, name: $name}';
}
}
Why not simply use cloud code ? I'm not to familiar with flutter but I can suggest you this alternative solution.
Write a function like this.
Parse.Cloud.define("fetchMemberAndUser", async (request) => {
//Pass in ParseResponse_OfficeObject ID as parameter
var objectId = request.params.id;
//Now do a simple get query
var query = new Parse.Query(Parse.Object.extend("Office_Members"));
//Using .includes to get the user profile object
query.include("user_id");
//This will return Office_Memebers Object along with user profile
return query.get(objectId,{useMasterKey:true});
}
graphql_flutter return LazyCacheMap, built_value deserializeWith JSON String, how to make them work together.
I use graphql_flutter to fetch data, and response give the result data as LazyCacheMap.
And using built_value for data model & data serialization, but since deserializeWith working with JSON String.
What's the best way to work with them together ?
Should I just convert LazyCacheMap's data of to String and call deserializeWith ?
should I use other serialization pubs ?
First encode the response LazyCacheMap to JSON using the dart:convert package, then perform whatever operation you want.
import 'dart:convert';
GraphQLClient _client = graphQLConfiguration.clientToQuery();
QueryResult result = await _client.query(
QueryOptions(
documentNode: gql(GraphQlQueries.authenticateUser()),
)
);
print(jsonEncode(result.data));
Worked for me.
280/5000
I'm writing an app that read "Yesterday's" story with flutter. How to get data from the website "https://mylifengayhomqua.blogspot.com/2012/04/ngay-hom-qua-tung-chap-1.html". Specifically, get a list of chapters, chapter names, chapter contents for a listview.
First, you have to download the HTML code which you want to parse. You can do it by adding to your code a function like this:
import 'dart:convert';
import 'package:http/http.dart';
import 'package:html/parser.dart';
import 'package:html/dom.dart';
...
Future initiate() async {
var client = Client();
Response response = await client.get(
'https://mylifengayhomqua.blogspot.com/2012/04/ngay-hom-qua-tung-chap-1.html'
);
print(response.body);
return response.body;
}
There's a nice article about scraping HTML, you can find it here.
Then you have to find the right HTML selectors and parse the response.body in this way:
var document = parse(response.body);
List<Element> yourContent = document.querySelectorAll('your selector');
Converting to a map should be easy then and is nicely described in an article above.
Good luck <3
I have a app of google app engine for for java and it have a facebook form which on submitting send a signed_request to a servlet in our app. We are using following code to unencrypt and convert to a json string
String signedRequest = (String) req.getParameter("signed_request");
String payload = signedRequest.split("[.]", 2)[1];
payload = payload.replace("-", "+").replace("_", "/").trim();
String jsonString = new String(Base64.decodeBase64(payload.getBytes()));
System.out.println("Json is::" + jsonString);
The response looks like
[sakshumweb/3.361739372881481188].: Json is::{"algorithm":"HMAC-SHA256","expires":1347588000,"issued_at":1347584290,"oauth_token":"XXXXX","registration":{"name":"Vik Kumar","first_name":"Vik","last_name":"Kumar","bloodGroup":"B-","gender":"male","birthday":"10/31/1983","email":"vik.ceo\u0040gmail.com","cellPhone":"1234123456","homePhone":"1234123457","officePhone":"1234123458","primaryAddress":"jdfjfgj","area":"jfdjdfj","location":{"name":"Redwood Shores, California","id":103107903062719},"subscribe":true,"eyePledge":false,"reference":"fgfgfgfg"},
"registration_metadata":{"fields":"[{\"name\":\"name\"},{\"name\":\"first_name\"},{\"name\":\"last_name\"}, {\"name\":\"bloodGroup\", \"description\":\"Blood Group\", \"type\":\"select\", \"options\":{\"A+\":\"A+\",\"A-\":\"A-\",\"B+\":\"B+\",\"B-\":\"B-\",\"O+\":\"O+\",\"O-\":\"O-\",\"AB+\":\"AB+\",\"AB-\":\"AB-\",\"A1+\":\"A1+\",\"A1-\":\"A1-\",\"A2+\":\"A2+\",\"A2-\":\"A2-\",\"A1B+\":\"A1B+\",\"A1B-\":\"A1B-\",\"A2B+\":\"A2B+\",\"A2B-\":\"A2B-\",\"HH\":\"Bombay Blood Group\"}}, {\"name\":\"gender\"}, {\"name\":\"birthday\"},{\"name\":\"email\"}, {\"name\":\"cellPhone\", \"description\":\"Cell Number\", \"type\":\"text\"}, {\"name\":\"homePhone\", \"description\":\"Home Number\", \"type\":\"text\"}, {\"name\":\"officePhone\", \"description\":\"Office Number\", \"type\":\"text\"}, {\"name\":\"primaryAddress\", \"description\":\"Primary Address\", \"type\":\"text\"}, {\"name\":\"area\", \"description\":\"Locality/Village/Area\", \"type\":\"text\"},{\"name\":\"location\"}, {\"name\":\"subscribe\", \"description\":\"Subscribe me for the Sakshum activites updates.\", \"type\":\"checkbox\", \"default\":\"checked\"}, {\"name\":\"eyePledge\", \"description\":\"I want to pledge my eyes as well.\", \"type\":\"checkbox\"}, {\"name\":\"reference\", \"description\":\"How you reached to us (Friend, Facebook, google etc.)?\", \"type\":\"text\"}]"},"user":{"country":"us","locale":"en_GB"},"user_id":"875390603"}
So, how do i parse this data to extract the data in registration part of this response?
Since this is a valid JSON, you can use JSON library like Jackson or GSON to parse it.
You can use this example code to print out all registration fields:
JsonNode json = new ObjectMapper().readTree(response);
JsonNode registration_fields = json.get("registration");
Iterator<String> fieldNames = registration_fields.getFieldNames();
while(fieldNames.hasNext()){
String fieldName = fieldNames.next();
String fieldValue = registration_fields.get(fieldName).asText();
System.out.println(fieldName+" : "+fieldValue);
}