I've trying to getting some from information with a WS ,using get method.
I did managed to get the needed information from one WS,but not from a second one.
string url = "";
url = "http://...";
List<Client> listOfClient = null;
string host = url;
WebRequest req = WebRequest.Create(#host);
try
{
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
using (var reader = new StreamReader(resp.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
listOfClient = (List<Client>)js.Deserialize(objText, typeof(List<Client>));
}
}
name = listOfClient.FirstOrDefault().name;
return name;
}
catch (Exception)
{
throw;
}
Here is the Json :
[
{
"city": NY,
"age": 30,
"Name": "Robert",
}
]
I need to read the property offer using the same logic.
{
"contract": "480788888",
"numbers": [
{
"type": "IDEI",
"value": "5987699118"
}
],
"status": "Valid",
"offer": "PNE",
}
Using Newtonsoft.Json.Linq
dynamic obj= JObject.Parse("{ 'contract': '480788888', 'numbers': [ { 'type':
'IDEI', 'value': '5987699118' } ],'status': 'Valid', 'offer': 'PNE', }");
string offer = obj.offer;
Related
I tried to set params to picture.width(360).height(360)
const infoRequest = new GraphRequest(
'/me',
{
accessToken: tokenData.accessToken,
parameters: {
fields: {
string: 'id,email,name,picture.width(360).height(360)'
}
}
},
responseInfoCallback
);
but it returns an incorrect dimension 480x480
{
"profile":{
"picture":{
"data":{
"width":480,
"height":480,
"url":"https://scontent.fmnl3-1.fna.fbcdn.net/v/t1.30497-1/c141.0.480.480a/p480x480/84628273_176159830277856_972693363922829312_n.jpg?_nc_cat=1&_nc_sid=12b3be&_nc_eui2=AeF95aCnm2ggUPNPmTv9zCouik--Qfnh2B6KT75B-eHYHvMDChmr6ZbCJUK-KjNtt6PEAlHLBWx9GsGneBpfz-Jm&_nc_ohc=VQqsNSqP_MgAX_0Hjw6&_nc_ht=scontent.fmnl3-1.fna&oh=f11455cd5e09ac5466f5b7590d489e7e&oe=5EDF5715",
"is_silhouette":true
}
},
"id":"102794254765525",
"name":"Elizabeth Aleajdheafejh Fallerwitz",
"email":"swgqsfetew_1588681446#tfbnw.net"
}
}
any help would be much appreciated
You can use this .
const user = {
"name": getUser.name,
"firstName":getUser.first_name,
"lastName": getUser.last_name,
// "profileImage": getUser.picture.data.url,
profileImage:`http://graph.facebook.com/${getUser.id}/picturetype=large&redirect=true&width=500&height=500`,
"token": data.accessToken,
}
if any problem you may ask.
I have a futurebuilder that builds the UI based on a List, it does the job, however I get duplicates due to the UI being built again and again whenever I navigate. My question is, is there a innate method in Dart that can remove duplicates from a list? I've tried this StackOverflow question however it doesn't work.
Here is my custom model:
class HomeList {
Widget navigateScreen;
String imagePath;
PatientInfo patientInfo;
HomeList({
this.navigateScreen,
this.imagePath = '',
this.patientInfo,
});
static List<HomeList> homeList = [];
}
Here is my function for the futureBuilder i'm getting the data from my cloud_firestore:
_getPatients() async {
if (didLoadpatients == 0) {
print('this is didloadpatients at start of func $didLoadpatients');
var document = await db
.collection('users')
.document(mUser.uid)
.collection('patients');
document.getDocuments().then((QuerySnapshot query) async {
query.documents.forEach((f) {
uids.add(f.data['uID']);
});
didLoadpatients++;
print('this is didloadpatients at end of func $didLoadpatients');
for (var i = 0; i < uids.length; i++) {
var userDocuments = await db.collection('users').document(uids[i]);
userDocuments.get().then((DocumentSnapshot doc) {
print(doc.data);
homeList.add(HomeList(
imagePath: 'assets/fitness_app/fitness_app.png',
patientInfo: new PatientInfo.fromFbase(doc.data)));
});
print(homeList);
}
});
} else
print('I am leaving the get patient function');
}
Future<bool> getData() async {
_getCurrentUser();
await Future.delayed(const Duration(milliseconds: 1500), () async {
_getPatients();
});
return true;
}
Any help would be appreciated thank you!
To remove duplicates you can use Set Data Structure instead of List.
Just use Set instead of List to get unique values only.
Before Adding you can Remove Element from model this will Work
dummymodel.removeWhere((m) => m.id == id);
dummymodel.add(dummymodel.fromJson(data));
To Remove Duplicates from Data Model simply use Set (Data structure),
Original List with Duplicate Entries:
List<MyDataModel> mList = [MyDataModel(1), MyDataModel(2), MyDataModel(1), MyDataModel(3)];
New List that removes duplicate Entries from your List<MyDataModel>:
List<MyDataModel> mNewList = list.toSet().toList();
Output:
The result will be like
MyDataModel(1), MyDataModel(2), MyDataModel(3)
To remove the duplicate elements from custom object list, you need to override == and hashcode methods in your POJO class and then add the items in Set and again convert set to list to remove duplicate objects. Below is the working code:-
class TrackPointList {
double latitude;
double longitude;
String eventName;
Time timeZone;
TrackPointList({
this.latitude,
this.longitude,
this.eventName,
this.timeZone,
});
#override
bool operator==(other) {
// Dart ensures that operator== isn't called with null
// if(other == null) {
// return false;
// }
if(other is! TrackPointList) {
return false;
}
// ignore: test_types_in_equals
return eventName == (other as TrackPointList).eventName;
}
int _hashCode;
#override
int get hashCode {
if(_hashCode == null) {
_hashCode = eventName.hashCode;
}
return _hashCode;
}
factory TrackPointList.fromJson(Map<String, dynamic> json) => TrackPointList(
latitude: json["latitude"].toDouble(),
longitude: json["longitude"].toDouble(),
eventName: json["eventName"],
timeZone: timeValues.map[json["timeZone"]],
);
Map<String, dynamic> toJson() => {
"latitude": latitude,
"longitude": longitude,
"eventName": eventName,
"timeZone": timeValues.reverse[timeZone],
};
}
Above is the POJO class. Now below is the method which helps you to filter the objects according to the eventName data member.
List<TrackPointList> getFilteredList(List<TrackPointList> list){
final existing = Set<TrackPointList>();
final unique = list
.where((trackingPoint) => existing.add(trackingPoint))
.toList();
return unique;
}
This will work definitely.
Please +1 if it helps you.
I've come up with quite a brute force solution. Instead of
_getPatients() async {
if (didLoadpatients == 0) {
print('this is didloadpatients at start of func $didLoadpatients');
var document = await db
.collection('users')
.document(mUser.uid)
.collection('patients');
document.getDocuments().then((QuerySnapshot query) async {
query.documents.forEach((f) {
uids.add(f.data['uID']);
});
didLoadpatients++;
print('this is didloadpatients at end of func $didLoadpatients');
for (var i = 0; i < uids.length; i++) {
var userDocuments = await db.collection('users').document(uids[i]);
userDocuments.get().then((DocumentSnapshot doc) {
print(doc.data);
homeList.add(HomeList(
imagePath: 'assets/fitness_app/fitness_app.png',
patientInfo: new PatientInfo.fromFbase(doc.data)));
});
print(homeList);
}
});
} else
print('I am leaving the get patient function');
}
I've done what #Jay Mungara says and clear my Set everytime my UI rebuilds:
_getPatients() async {
homeList.clear();
if (didLoadpatients == 0) {
print('this is didloadpatients at start of func $didLoadpatients');
var document = await db
.collection('users')
.document(mUser.uid)
.collection('patients');
document.getDocuments().then((QuerySnapshot query) async {
query.documents.forEach((f) {
uids.add(f.data['uID']);
});
didLoadpatients++;
print('this is didloadpatients at end of func $didLoadpatients');
for (var i = 0; i < uids.length; i++) {
var userDocuments = await db.collection('users').document(uids[i]);
userDocuments.get().then((DocumentSnapshot doc) {
print(doc.data);
homeList.add(HomeList(
imagePath: 'assets/fitness_app/fitness_app.png',
patientInfo: new PatientInfo.fromFbase(doc.data)));
});
print(homeList);
}
});
} else
print('I am leaving the get patient function');
}
Thank you for all your answers!
this is a small examples to remove duplicate element
removeDuplicate() {
List<dynamic> demoList = [
{"userId": 1, "id": 1, "name": "thappu1"},
{"userId": 2, "id": 2, "name": "appu"},
{"userId": 1, "id": 1, "name": "thappu1"},
{"userId": 2, "id": 2, "name": "appu"},
{"userId": 2, "id": 2, "name": "appu"},
{"userId": 2, "id": 2, "name": "appu"},
{"userId": 2, "id": 2, "name": "appu"},
];
var toRemove = {};
demoList.forEach((e) {
toRemove.putIfAbsent("$e", () => e);
});
print(toRemove.keys.toList());
}
output is
[{userId: 1, id: 1, name: thappu1}, {userId: 2, id: 2, name: appu}]
I just created my first album via api, uploaded a picture and added to to my new album. But how can I specify the timezone, the camera data, the location, etc?
Do I really need to embed those information via exif? In that case I would need to manipulate the image data which I want to avoid.
This is my workaround. I add the information via exif in nodejs:
request.get('http://example.com/foto.jpg')
.pipe(exifEnricher)
.pipe(request.post('https://photoslibrary.googleapis.com/v1/uploads', {
headers: {
'User-Agent': 'MyService',
'Authorization': 'Bearer ' + token,
'Content-type': 'application/octet-stream',
'X-Goog-Upload-File-Name': 'Filename.jpg',
'X-Goog-Upload-Protocol': 'raw'
}
}, function(error, uploadResponse, uploadToken) {
if(error) {
response.end(error);
} else {
request.post('https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate', {
headers: {
'User-Agent': 'MyService',
'Authorization': 'Bearer ' + token,
'Content-type': 'application/json'
},
json: {
"albumId": "abcdef...",
"newMediaItems": [
{
"description": "Haustür X",
"simpleMediaItem": {
"uploadToken": uploadToken
}
}
],
"albumPosition": {
"position": "FIRST_IN_ALBUM"
}
}
}, (error, addToAlbumResponse, addToAlbumBody) => {
if(error) {
response.end(error);
} else {
response.end(JSON.stringify(addToAlbumBody));
}
});
}
}));
const exifEnricher = new Transform({
transform(chunk, encoding, callback) {
if(chunk[0] === 255 && chunk[1] === 216) {
const data = chunk.toString("binary");
const exifObj = piexif.load(data);
exifObj["GPS"][piexif.GPSIFD.GPSVersionID] = [2, 2, 0, 0];
exifObj["GPS"][piexif.GPSIFD.GPSLatitudeRef] = "N";
exifObj["GPS"][piexif.GPSIFD.GPSLatitude] = [[lat_degree, 1], [lat_minutes, 1], [lat_seconds_x_10, 10]];
exifObj["GPS"][piexif.GPSIFD.GPSLongitudeRef] = "E";
exifObj["GPS"][piexif.GPSIFD.GPSLongitude] = [[lon_degree, 1], [lon_minutes, 1], [lon_seconds_x_10, 10]];
exifObj["GPS"][piexif.GPSIFD.GPSAltitudeRef] = 0;
exifObj["GPS"][piexif.GPSIFD.GPSAltitude] = [alt_in_cm, 100];
exifObj["0th"] = exifObj["0th"] || {};
exifObj["0th"][piexif.ImageIFD.Software] = "MyService";
exifObj["0th"][piexif.ImageIFD.Make] = "Brand";
exifObj["0th"][piexif.ImageIFD.Model] = "Device Name";
exifObj["0th"][piexif.ImageIFD.DateTime] = dateFormat(new Date(), "yyyy:mm:dd HH:mm:ss");
const exifbytes = piexif.dump(exifObj);
const newData = piexif.insert(exifbytes, data);
callback(null, Buffer.from(newData, 'binary'))
} else {
callback(null, chunk)
}
}
});
I don't know where is problem
{
"success": "1",
"wallpapers": [
{
"id": "1",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/1477685052.jpg"
},
{
"id": "2",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/14776850521.jpg"
},
{
"id": "3",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/14776850522.jpg"
},
{
"id": "4",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/14776850523.jpg"
},
{
"id": "5",
"image": "http://cyphersol.com/apps/ringtona/uploads/gallery/14776850524.jpg"
}
]
}
I am using retrofit2.0
interface
public interface ApiInterface {
#POST("getImages")
Call<WallPaperResponse> getWallpapers(#Query("id") int apiKey);
}
Api Client
public class ApiClient {
public static final String BASE_URL = "http://cyphersol.com/apps/ringtona/webservice/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Call in to MainActivity
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<WallPaperResponse> call = apiService.getWallpapers(1);
call.enqueue(new Callback<WallPaperResponse>() {
#Override
public void onResponse(Call<WallPaperResponse> call, Response<WallPaperResponse> response) {
int statusCode = response.code();
List<WallpapersItem> wallpaper = response.body().getWallpapers();
for (int i = 0; i < wallpaper.size(); i++) {
Log.e(TAG, wallpaper.get(i).getImage());
}
// recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.list_item_movie, getApplicationContext()));
}
#Override
public void onFailure(Call<WallPaperResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
dependency
// retrofit, gson
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
I think This will help you.
KingController mWebController = KingController.getInstance(this);
String apiToken = "1"; mWebController.getMainCategories(apiToken);
#GET("getImages")
Call getWallpaperLis(#Header("id") String api_token);
Regargs
Rashid Ali
Your web service requires id to be sent as a HEADER
While you have rather sent it as a POST parameter.
Hence, Your web service did not return a valid response
and the error.
Let me know if this works.
public interface ApiInterface {
#GET("getImages")
Call<WallPaperResponse> getWallpapers(#Header("id") int apiKey);
}
P.S This site has solid documentation on retorfit
https://futurestud.io/tutorials/retrofit-2-manage-request-headers-in-okhttp-interceptor
I am getting xml output then i am converting that xml into json object.the format is given below.
{
"SOAP-ENV:Envelope": {
"#xmlns:SOAP-ENV": "http://schemas.xmlsoap.org/soap/envelope/",
"#xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"#xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"SOAP-ENV:Body": {
"rpc:TestExampleResponse": {
"#xmlns:rpc": "http://Test.com/asi/",
"TestMessage": {
"listOfTESTS": {
"#xmlns:xmlns": "http://www.Test.com/xml/TEST",
"TESTS": [{
"id": "1",
"lastSyncDate": "12/16/2015 07:06:38",
"listOfTESTsyncrealtimeChild": null
}, {
"id": "2",
"lastSyncDate": "12/16/2015 07:06:38",
"listOfTESTsyncrealtimeChild": null
}
]
}
}
}
}
}
}
i want to extract Test array from JSON Output in Mulesoft.I dont know how to extract that array in mulesoft.Thanks in advance
You can use Dataweave (Transform Message component in Anypoint Studio)
(Mule EE)
Take a look to the documentation:
https://docs.mulesoft.com/mule-user-guide/v/3.7/using-dataweave-in-studio
Sample script for your input:
%dw 1.0
%input payload application/json
%output application/json
---
TESTS: payload."SOAP-ENV:Envelope"."SOAP-ENV:Body"."rpc:TestExampleResponse".TestMessage.listOfTESTS.TESTS map ((tEST , indexOfTEST) -> {
id: tEST.id,
lastSyncDate: tEST.lastSyncDate,
listOfTESTsyncrealtimeChild: tEST.listOfTESTsyncrealtimeChild
})
Output when using %output application/json:
{
"TESTS": [
{
"id": "1",
"lastSyncDate": "12/16/2015 07:06:38",
"listOfTESTsyncrealtimeChild": null
},
{
"id": "2",
"lastSyncDate": "12/16/2015 07:06:38",
"listOfTESTsyncrealtimeChild": null
}
]
}
Output when using %output application/java:
{TESTS=[{id=1, lastSyncDate=12/16/2015 07:06:38, listOfTESTsyncrealtimeChild=null}, {id=2, lastSyncDate=12/16/2015 07:06:38, listOfTESTsyncrealtimeChild=null}]}
You can write a custom transformer like below. This transformer uses Jackson (com.fasterxml.jackson) dependency.
The transformer returns a list of strings where each string represents an element of your TESTS array.
public class JsonArrayExtractor extends AbstractTransformer {
private final ObjectMapper mapper = new ObjectMapper();
private final String testsNodeJsonPointer = "/SOAP-ENV:Envelope/SOAP-ENV:Body/rpc:TestExampleResponse/TestMessage/listOfTESTS/TESTS";
public JsonArrayExtractor() {
registerSourceType(DataTypeFactory.STRING);
}
#Override
protected Object doTransform(Object src, String enc) throws TransformerException {
String payload = Objects.toString(src);
JsonNode root;
try {
root = mapper.readTree(payload);
} catch (IOException e) {
throw new TransformerException(this, e);
}
List<String> testsList = new ArrayList<>();
JsonNode testsNode = root.at(JsonPointer.valueOf(testsNodeJsonPointer));
if (testsNode instanceof ArrayNode) {
ArrayNode testsArrayNode = (ArrayNode) testsNode;
for (JsonNode test : testsArrayNode) {
testsList.add(test.toString());
}
}
return testsList;
}
}
And you can use the above transformer in your flow as below.
<custom-transformer class="org.ram.JsonArrayExtractor" doc:name="extractTestsArray"/>