Cannot deserialize the current JSON object - Newtonsoft - class

I'm having problems resolving this error message. I've looked at some other answers on here and changed some things but I still receive this error:
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Clocker.Models.PeopleLocationForUser]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
This is my class:
namespace Clocker.Models
{
public class PeopleLocationForUser
{
string locationPeople { get; set; }
public users users { get; set; }
}
public class users
{
public int EB_Counter { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int TATokenValue { get; set; }
}
}
This is the method that errors on the deserialize line:
public static async Task<PeopleLocationForUser> GetPeopleLocationForUser(string UserName, int LocationId)
{
Uri uri = new Uri(URL + "GetPeopleLocationForUser" + "?username=" + UserName + "&locationid=" + LocationId);
HttpClient myClient = new HttpClient();
var response = await myClient.GetAsync(uri);
var content = await response.Content.ReadAsStringAsync();
var test = JsonConvert.DeserializeObject<List<PeopleLocationForUser>>(content);
//return something when it's working
return null;
}
This is the start of the Json data:
{"result":true,"locationPeople":[{"EB_Counter":101,"FirstName":"RSS","LastName":"13.11.1","TATokenValue":"TS_101_1_RSS_SWIPE"},{"EB_Counter":102,"FirstName":"RSS","LastName":"13.11.2","TATokenValue":"TS_102_1_RSS_SWIPE"},{"EB_Counter":93,"FirstName":"RSS","LastName":"13.7.1","TATokenValue":"TS_93_1_RSS_SWIPE"},{"EB_Counter":94,"FirstName":"RSS","LastName":"13.7.10","TATokenValue":"TS_94_1_RSS_SWIPE"},{"EB_Counter":95,"FirstName":"RSS","LastName":"13.8.2","TATokenValue":"TS_95_1_RSS_SWIPE"},{"EB_Counter":99,"FirstName":"RSS","LastName":"13.9.2","TATokenValue":"TS_99_1_RSS_SWIPE"},
This is what my Json data looks like when it arrives:
I hope you can help. The end result is that I'm trying to get this data into a list so I can use it in a Xamarin ListView.

You are receiving list and in the class you are expecting just one instance of user, this is how the class should be:
public class LocationPeople
{
public int EB_Counter { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string TATokenValue { get; set; }
}
public class RootObject
{
public bool result { get; set; }
public List<LocationPeople> locationPeople { get; set; }
}
var test = JsonConvert.DeserializeObject<RootObject>(content);

Related

Failing to pass a complex object from one page to another in .Net Maui

I am trying to pass a complex object from MainPage to a ProductsPage, the object is a model with 4 class lists. Of the 4 class lists only 2 are passing data to the ProductsPage, the other 2 are not. I dont know where i am going wrong, i am using MVVM
My MainPageViewModel is as below
public partial class MainPageViewModel : BaseViewModel
{
public ObservableCollection<LogInModel> LogInModels { get; } = new();
public MainPageViewModel()
{
}
[ObservableProperty]
LogInModel logInModel;
[RelayCommand]
async Task GoToRetailAsync()
{
if (LogInModels.Count != 0)
LogInModels.Clear();
LogInModels.Add(logInModel);
await Shell.Current.GoToAsync($"{nameof(ProductsPage)}", true,
new Dictionary<string, object>
{
{"shiptoo",LogInModels[0].cat },
{"group",LogInModels[0].grp },
{"products",LogInModels[0].prod },
{"shipto",LogInModels[0].shp }
});
}
}
}
the failing class lists are shiptoo and group
Below is my ProductsViewModel
namespace Tenga.ViewModel
{
[QueryProperty("Products", "products")]
[QueryProperty("Group","group")]
[QueryProperty("Shiptoo","shiptoo")]
[QueryProperty("Shipto", "shipto")]
public partial class ProductsViewModel : BaseViewModel
{
public ProductsViewModel()
{
}
[ObservableProperty]
List<Shiptoo> shppp;
[ObservableProperty]
List<Group> groups;
[ObservableProperty]
List<Products> products;
[ObservableProperty]
List<Shipto> shipto;
}
}
Below is my LogInModel
namespace Tenga.Model
{
public class LogInModel
{
public string OTP { get; set; }
public string CustomerNumber { get; set; }
public string CustomerName { get; set; }
public string Balance { get; set; }
public string OpenToBuy { get; set; }
public string CreditLimit { get; set; }
public string LoginStatus { get; set; }
public string Error { get; set; }
public List<Shipto> shp = new List<Shipto>();
public List<Shiptoo> cat = new List<Shiptoo>();
public List<Group> grp = new List<Group>();
public List<Products> prod = new List<Products>();
}
public class Shipto
{
public string ShipCode { get; set; }
public string ShipDescription { get; set; }
}
public class Products
{
public string ItemCode { get; set; }
public string ItemDescription { get; set; }
public string UOM { get; set; }
public string ConversionFactor { get; set; }
public string Category { get; set; }
public string Group { get; set; }
public byte[] Image { get; set; }
}
public class Shiptoo
{
public string ShipCode { get; set; }
public byte[] Image { get; set; }
}
public class Group
{
public string Category { get; set; }
public string Code { get; set; }
public byte[] Image { get; set; }
}
}
I have tried to review the class all seems alright, i have also tried changing the bindings and result is the same, can some one please help before go crazy
Implement IQueryAttributable in your ViewModel.
And use:
public void ApplyQueryAttributes(IDictionary<string, object> query)
{
Model = query[nameof(MyModel )] as MyModel ;
}
Forget about those annotations. This is better. You cant mistake names, you can run code after/before they are set. I migrated all my code to use this.
Edit: While we are on the subject:
Instead of:
{"shiptoo",LogInModels[0].cat },
You should be using some constants. The name of the model usually. (Something like naming conventions when passing Extras in android, but much more simple).

Xamarin Forms Plugin.CloudFirestore - How to Handle Firestore Map Fields and Firestore Map Arrays with Reactive

I am currently using the Plugin.CloudFirestore.Sample project (link: https://github.com/f-miyu/Plugin.CloudFirestore) as a reference for creating my own application and would like to know how I should code my project to upload documents containing Firestore Maps and Firestore Arrays that have nested Firestore Maps then listen for document changes and display these changes using Xamarin Forms, Plugin.CloudFirestore, and Reactive. I would also like to know the maximum amount of Map conversions that can be handled at a time while converting from a Firestore Document to a .Net Model Class. To clarify, if the ExampleItem Class mentioned below contains another Model Class as a property, how would the class and reactive class viewmodel code look to upload/listen for changes. If anyone knows the answer to my question, it would be awesome if you could download the Plugin.CloudFirestore.Sample project, make the changes to the file, share a response explaining what you added, and share a download link.
public class TodoItem
{
public static string CollectionPath = "todoItems";
//Should I use DocumentConverters for converting to the "DataMap" and "DataMapArray" properties? If so what would the code for them look like?
[Id]
public string? Id { get; set; }
public string? Name { get; set; }
public string? Notes { get; set; }
public ExampleItem1? DataMap { get; set; }
public ObservableCollection<ExampleItem1>? DataMapArray { get; set; }
[ServerTimestamp(CanReplace = false)]
public Timestamp CreatedAt { get; set; }
[ServerTimestamp]
public Timestamp UpdatedAt { get; set; }
}
public class ExampleItem1
{
// Should I use [Id] on the Id property or any other Plugin.CloudFirestore.Attributes?
public string? Id { get; set; }
public string? Name { get; set; }
public ExampleItem2? DataMap { get; set; }
public ObservableCollection<ExampleItem2>? DataMapArray { get; set; }
}
public class TodoItemViewModel : BindableBase
{
public string? Id { get; }
public ReactivePropertySlim<string?> Name { get; set; } = new ReactivePropertySlim<string?>();
public ReactivePropertySlim<string?> Notes { get; set; } = new ReactivePropertySlim<string?>();
public ReactivePropertySlim<ExampleItem?> DataMap { get; set; } = new ReactivePropertySlim<ExampleItem?>();
public ReactivePropertySlim<ObservableCollection<ExampleItem>?> DataMapArray { get; set; } = new ReactivePropertySlim<ObservableCollection<ExampleItem>?>();
public TodoItemViewModel(TodoItem item)
{
Id = item.Id;
Name.Value = item.Name;
Notes.Value = item.Notes;
DataMap.Value = item.DataMap;
DataMapArray.Value = item.DataMapArray;
}
public void Update(string? name, string? notes, ExampleItem1? dataMap, ObservableCollection<ExampleItem1>? dataMapArray)
{
Name.Value = name;
Notes.Value = notes;
DataMap.Value = dataMap;
DataMapArray.Value = dataMapArray;
}
}

Web API Get with query parameters on Mongodb collection

I have WebAPI written and it is using mongodb collection as a database.
it looks like
[
{
"Id":"5a449c148b021b5fb4cb1f66",
"airline":[
{
"airlineID":-1,
"airlineName":"Unknown",
"airlineAlias":"",
"airlineIATACode":"-",
"airlineICAOCode":"N/A",
"airlineCallsign":"",
"airlineBaseCountry":"",
"airlineActiveIndicator":"Y"
},
{
"airlineID":1,
"airlineName":"Private flight",
"airlineAlias":"",
"airlineIATACode":"1T",
"airlineICAOCode":"N/A",
"airlineCallsign":"",
"airlineBaseCountry":"",
"airlineActiveIndicator":"Y"
},
{
"airlineID":2,
"airlineName":"135 Airways",
"airlineAlias":"",
"airlineIATACode":"2T",
"airlineICAOCode":"GNL",
"airlineCallsign":"GENERAL",
"airlineBaseCountry":"United States",
"airlineActiveIndicator":"N"
}
]
}
]
I'm trying to get data using airlineIATACode attribute
public airlineModel Get(string i)
{
_collection = _db.GetCollection<airlineModel>("airline");
var res = Query<airlineModel>.EQ(p => p.airline[0].airlineIATACode, i);
return _collection.FindOne(res);
}
My controller implementation
public HttpResponseMessage Get(string IATAcode)
{
var result = objds.Get(IATAcode);
if (result != null)
return Request.CreateResponse(HttpStatusCode.OK, result);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Data not found");
}
My Model class:
public class airlineModel
{
public ObjectId Id { get; set; }
[BsonElement("airline")]
public List<airlinedata> airline { get; set; }
}
public class airlinedata
{
[BsonElement("airlineID")]
public int airlineID { get; set; }
[BsonElement("airlineName")]
public string airlineName { get; set; }
[BsonElement("airlineAlias")]
public string airlineAlias { get; set; }
[BsonElement("airlineIATACode")]
public string airlineIATACode { get; set; }
[BsonElement("airlineICAOCode")]
public string airlineICAOCode { get; set; }
[BsonElement("airlineCallsign")]
public string airlineCallsign { get; set; }
[BsonElement("airlineBaseCountry")]
public string airlineBaseCountry { get; set; }
[BsonElement("airlineActiveIndicator")]
public string airlineActiveIndicator { get; set; }
}
When I run app and browse http://localhost:60387/api/airlineAPI?IATAcode=1T
it says, Data not found
What can I do to solve this problem?
You can try this.
public airlinedata Get(string i)
{
var _collection = database.GetCollection<airlineModel>("airline");
var filter = Builders<airlineModel>.Filter
.ElemMatch(model => model.airline, airline => airline.airlineIATACode == i);
var projection = Builders<airlineModel>.Projection
.Include(model => model.airline[-1]);
var airlineModel = _collection.Find(filter)
.Project<airlineModel>(projection)
.Single();
return airlineModel.airline.Single();
}
Note that you don't need to put mapping attributes on each field. The default mapping does exactly what you did with attributes.
The only attribute I suggest you to use is [BsonId] to tell MongoDB which is your _id field.
public class airlineModel
{
[BsonId(IdGenerator = typeof(ObjectIdGenerator))]
public ObjectId Id { get; set; }
...
}
Finally, in case of a large collection, don't forget to create an index on airlineIATACode field, otherwise the search would perform an expensive COLLSCAN.

LiteDB null reference on insert

I ran into this problem where in I get a null reference exception on insert.
I have two object Models UserInfo and UserConfig. On the first trial, UserConfig references a UserInfo instance
public class UserConfigObject : IUserConfig
{
BsonRef("userInfo")]
public IUserInfo UserInfo { get; set; }
public string AssignedJob { get; set; }
public string[] QueueItems { get; set; }
}
public class UserInfoObject : IUserInfo
{
[BsonId]
public int ID { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string IPAddress { get; set; }
}
And a method to insert the data into the database
public void AddUser(IUserConfig user)
{
var uconCollection = DatabaseInstance.GetCollection<IUserConfig>("userConfig");
var uinCollection = DatabaseInstance.GetCollection<IUserInfo>("userInfo");
uinCollection.Insert(user.UserInfo);
uconCollection.Insert(user);
}
This set up works fine but when I try to change the reference to UserInfo references UserConfig
public class UserInfoObject : IUserInfo
{
[BsonId]
public int ID { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string IPAddress { get; set; }
[BsonRef("userConfig")]
public IUserConfig UserConfig { get; set; }
}
public class UserConfigObject : IUserConfig
{
[BsonRef("userInfo")]
public IUserInfo UserInfo { get; set; }
[BsonId(true)]
public int ConfigID { get; set; }
public string AssignedJob { get; set; }
public string[] QueueItems { get; set; }
}
With a method call for
public void AddUser(IUserInfo user)
{
var uconCollection = DatabaseInstance.GetCollection<IUserConfig>("userConfig");
var uinCollection = DatabaseInstance.GetCollection<IUserInfo>("userInfo");
uconCollection.Insert(user.UserConfig);
uinCollection.Insert(user);
}
It no longer works, it throws an System.NullReferenceException: 'Object reference not set to an instance of an object.' on uinCollection.Insert(user);
Either v3 or v4, it doesn't work with the latter set up
Had the same problem but with collections. I've tried to save collection of invitations like so:
using var db = new LiteRepository(_connectionString);
var invitations = new List<Invitation>
{
// populate list
};
db.Insert(invitations);
The problem is that T parameter resolved as IEnumerable<Invitation> not just Invitation, so if you are inserting a collection, set type explicitly.
db.Insert<Invitation>(invitations);

Post Json Data to Rest API

I'm developing WP8 app and i'm new to it.. i want to know my post method is correct or not because i'm unable to post my data in the url it produces an exception..
My Class Contents...
public class Register
{
public int id { get; set; }
public string password_reset_hash { get; set; }
public string temp_password { get; set; }
public bool remember_me { get; set; }
public string activation_hash { get; set; }
public string ip_address { get; set; }
public bool status { get; set; }
public bool activated { get; set; }
public string permissions { get; set; }
public DateTime last_login { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public string email { get; set; }
public string password { get; set; }
public string conformpassword { get; set; }
public string username { get; set; }
}
here is my code..
public void btn_register_click(object sender, RoutedEventArgs e)
{
string url="myurl";
Register res=new Register();// my class
res.email = txt_email.Text;
res.password = txt_password.Text;
res.conformpassword = txt_conf_psswrd.Text;
res.username = txt_username.Text;
res.created_at = DateTime.Now;
res.last_login = DateTime.Now;
res.updated_at = DateTime.Now;
res.status = true;
json = JsonConvert.SerializeObject(res);
WebClient wc = new WebClient();
var URI = new Uri(url);
wc.Headers["Content-Type"] = "application/json";
wc.Headers["ACCEPT"] = "application/json";
wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
wc.UploadStringAsync(URI, "POST", json);
}
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
MessageBox.Show(e.Result);
//e.result fetches you the response against your POST request.
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString()); //i'm getting error here..
}
}
My Screen Design..
Error is..
Thanks
It looks to me like there is a problem with the URI you are using. The error message you posted shows the server returning a "Not found" header. Maybe it just is not quite correct? I did not see the exact URI in the code you posted. string url="myurl"; does not look like this is the url you want to use.
That's also why you can't access the response stream without an exception with this line: MessageBox.Show(e.Result);. There just is no valid response. This is documented here: http://msdn.microsoft.com/de-de/library/system.net.uploadstringcompletedeventargs.result%28v=vs.110%29.aspx.
You can determine if such an error occurred by checking the Error property of UploadStringCompletedEventArgs (http://msdn.microsoft.com/de-de/library/system.net.uploadstringcompletedeventargs%28v=vs.110%29.aspx).