I have a problem that an index I've made when queried is throwing an exception :
Could not read value for property: Members
Here is the index :
public class GroupsNameIdIndex : AbstractIndexCreationTask<CommunityDocument, GroupsNameIdIndex.Result>
{
public class Result
{
public string CommunityId { get; set; }
public string Id { get; set; }
public string Name { get; set; }
public IList<string> Members { get; set; }
}
public GroupsNameIdIndex()
{
Map = communities => from community in communities
from newGroup in community.Groups
select new
{
CommunityId = community.Id.Replace("CommunityDocuments/", string.Empty),
newGroup.Id,
newGroup.Name,
newGroup.Members
};
StoreAllFields(FieldStorage.Yes);
}
}
This is the query :
var groupResult = session
.Query<GroupsNameIdIndex.Result, GroupsNameIdIndex>()
.Where(x => x.CommunityId == info.Id)
.AsProjection<GroupsNameIdIndex.Result>()
.ToList();
I only have 1 group in the document with relevant Id and the Members node is an empty list, not null. When I manually populate it with a single string, then the query runs fine. Why are empty lists not allowed? If this is a restriction, it makes indexing pointless for me, because I will have a lot of empty lists that are just going to make the application fail everywhere.
edit: Adding the class in case that has something to do with it:
public class CommunityGroup
{
public CommunityGroup()
{
Members = new List<string>();
MemberDetails = new List<MemberView>();
MemberNames = new List<string>();
}
public string Id { get; set; }
public string Name { get; set; }
public string Slug { get; set; }
public string Description { get; set; }
public bool AdminOnly { get; set; }
public bool NewsContribute { get; set; }
public bool AutoGroup { get; set; }
public int LowerAgeLimit { get; set; }
public int UpperAgeLimit { get; set; }
public string Gender { get; set; }
public IList<string> Members { get; set; }
public IList<string> MemberNames { get; set; }
public IList<MemberView> MemberDetails { get; set; }
public string RelatedCommunityId { get; set; }
public string CreatedBy { get; set; }
public bool SmartGroup { get; set; }
public IList<SmartGroupRules> AndRules { get; set; }
public IList<SmartGroupRules> OrRules { get; set; }
public string ParentGroup { get; set; }
public List<string> EntryGroups { get; set; }
public bool Hidden { get; set; }
public string ActivityType { get; set; }
public List<string> AnyGroupList { get; set; }
public List<string> AllGroupList { get; set; }
public GroupType GroupType { get; set; }
}
and here is the json of the group in the db
"Groups": [
{
"Id": "5ja34tefoq7sfj",
"Name": "new test",
"Slug": "new-test",
"Description": null,
"AdminOnly": true,
"NewsContribute": false,
"AutoGroup": false,
"LowerAgeLimit": 0,
"UpperAgeLimit": 0,
"Gender": null,
"Members": [],
"MemberNames": [],
"MemberDetails": [],
"RelatedCommunityId": null,
"CreatedBy": "Activity",
"SmartGroup": false,
"AndRules": null,
"OrRules": null,
"ParentGroup": null,
"EntryGroups": null,
"Hidden": false,
"ActivityType": null,
"AnyGroupList": null,
"AllGroupList": null,
"GroupType": "Default"
}
],
Related
I'm using EFCore (With Cosmos), and for some reason it's adding a 2nd key for me, on the convention of id, despite having a property name Id, with the KeyAttribute.
Anyway I can stop this?
public class User
{
public User()
{
}
public User(ClaimsPrincipal principal)
{
Id = principal.FindFirst(ClaimTypes.NameIdentifier).Value;
FirstName = principal.FindFirst(ClaimTypes.GivenName).Value;
Surname = principal.FindFirst(ClaimTypes.Surname).Value;
Email = principal.FindFirst(ClaimTypes.Email).Value;
}
[Key]
public string Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime LastLoginTime { get; set; }
public Company Company { get; set; }
public User CreatedBy { get; set; }
//Hack to get around EF/Cosmos Enum error
private string UserType { get; set;}
[NotMapped]
public UserType UserTypeEnum
{
get
{
if (string.IsNullOrWhiteSpace(UserType))
{
return Models.UserType.User;
}
return (UserType)Enum.Parse(typeof(UserType), UserType);
}
set
{
UserType = value.ToString();
}
}
}
You can add [Newtonsoft.Json.JsonProperty(PropertyName="id")] above your Id property
Link
I have a complex model of data based on reading in a JSON file which has a collection of objects, properties and arrays.
I am reading my data into a model which I am populating with design-time data and instantiating in my UWP project in XAML like this:
<local:UntappdUserInfoSampleData x:Key="data1" />
I want to set the ItemsSource for a ListView control to a collection in my model but I'm not sure how to reference it in my data Binding.
My object model has this structure:
user
checkins
items[]
venue
venue_name
comments
badges
items[]
badge_id
badge_description
badge_image
small
medium
large
I want to get to badge_image.small within that stack as a Binding within my XAML.
I know how to get to higher level data like this to get to checkins.items[]:
<ListView x:Name="lvRecenCheckins"
d:DataContext="{StaticResource data1}"
ItemsSource="{Binding checkins.items}"
CanDragItems="False"
IsItemClickEnabled="True"
IsSwipeEnabled="False"
SelectionMode="None" ItemTemplate="{StaticResource RecentCheckinsTemplate}" Grid.Row="1"
/>
But how can I get all the way down to the items collection for checkins.items[].badges.items[]?
I can get to the collection I want in code behind with this as an example:
UntappdUserInfoSampleData usersampleinfo = new UntappdUserInfoSampleData();
string iii2 = usersampleinfo.checkins.items[].badges.items[0].badge_image.small;
I want to bind a different ListView to checkins.items[].badges.items[]
How can I do that?
Here are the data classes:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace UntappdExplorer
{
public class UntappdUserInfoSampleData : User_User {
public UntappdUserInfoSampleData()
{
string[] names = this.GetType().GetTypeInfo().Assembly.GetManifestResourceNames();
Stream stream = this.GetType().GetTypeInfo().Assembly.GetManifestResourceStream("UntappdExplorer.DataModel.ricke_User_info.json");
string result = String.Empty;
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
var resolver = new DefaultContractResolver(); // Cache for performance
var Serializersettings = new JsonSerializerSettings
{
ContractResolver = resolver,
Converters = { new IgnoreUnexpectedArraysConverter(resolver) },
};
User_RootObject rootJSON = JsonConvert.DeserializeObject<User_RootObject>(result, Serializersettings);
User_User userinfo = rootJSON.response.user;
uid = userinfo.uid;
id = userinfo.id;
user_name = userinfo.user_name;
first_name = userinfo.first_name;
last_name = userinfo.last_name;
user_avatar = userinfo.user_avatar;
user_avatar_hd = userinfo.user_avatar_hd;
user_cover_photo = userinfo.user_cover_photo;
user_cover_photo_offset = userinfo.user_cover_photo_offset;
is_private = userinfo.is_private;
location = userinfo.location;
url = userinfo.url;
bio = userinfo.bio;
is_supporter = userinfo.is_supporter;
is_moderator = userinfo.is_moderator;
relationship = userinfo.relationship;
block_status = userinfo.block_status;
untappd_url = userinfo.untappd_url;
account_type = userinfo.account_type;
stats = userinfo.stats;
recent_brews = userinfo.recent_brews;
checkins = userinfo.checkins;
media = userinfo.media;
contact = userinfo.contact;
date_joined = userinfo.date_joined;
settings = userinfo.settings;
}
}
public class User_User
{
public int uid { get; set; }
public int id { get; set; }
public string user_name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string user_avatar { get; set; }
public string user_avatar_hd { get; set; }
public string user_cover_photo { get; set; }
public int user_cover_photo_offset { get; set; }
public int is_private { get; set; }
public string location { get; set; }
public string url { get; set; }
public string bio { get; set; }
public int is_supporter { get; set; }
public int is_moderator { get; set; }
public string relationship { get; set; }
public string block_status { get; set; }
public string untappd_url { get; set; }
public string account_type { get; set; }
public User_Stats stats { get; set; }
public User_RecentBrews recent_brews { get; set; }
public User_Checkins checkins { get; set; }
public User_Media2 media { get; set; }
public List<object> contact { get; set; }
public string date_joined { get; set; }
public User_Settings settings { get; set; }
}
public class User_RootObject
{
public User_Meta meta { get; set; }
public User_Notifications notifications { get; set; }
public User_Response response { get; set; }
}
public class User_Response
{
public User_User user { get; set; }
}
public class User_ResponseTime
{
public double time { get; set; }
public string measure { get; set; }
}
public class User_InitTime
{
public int time { get; set; }
public string measure { get; set; }
}
public class User_Meta
{
public int code { get; set; }
public User_ResponseTime response_time { get; set; }
public User_InitTime init_time { get; set; }
}
public class User_UnreadCount
{
public int comments { get; set; }
public int toasts { get; set; }
public int friends { get; set; }
public int messages { get; set; }
public int venues { get; set; }
public int veunes { get; set; }
public int others { get; set; }
public int news { get; set; }
}
public class User_Notifications
{
public string type { get; set; }
public User_UnreadCount unread_count { get; set; }
}
public class User_Stats
{
public int total_badges { get; set; }
public int total_friends { get; set; }
public int total_checkins { get; set; }
public int total_beers { get; set; }
public int total_created_beers { get; set; }
public int total_followings { get; set; }
public int total_photos { get; set; }
}
public class User_Beer
{
public int bid { get; set; }
public string beer_name { get; set; }
public string beer_label { get; set; }
public double beer_abv { get; set; }
public string beer_description { get; set; }
public string beer_style { get; set; }
public double auth_rating { get; set; }
public bool wish_list { get; set; }
}
public class User_Contact
{
public string twitter { get; set; }
public string facebook { get; set; }
public string instagram { get; set; }
public string url { get; set; }
}
public class User_Location
{
public string brewery_city { get; set; }
public string brewery_state { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Brewery
{
public int brewery_id { get; set; }
public string brewery_name { get; set; }
public string brewery_slug { get; set; }
public string brewery_label { get; set; }
public string country_name { get; set; }
public User_Contact contact { get; set; }
public User_Location location { get; set; }
public int brewery_active { get; set; }
}
public class User_Item
{
public User_Beer beer { get; set; }
public User_Brewery brewery { get; set; }
}
public class User_RecentBrews
{
public int count { get; set; }
public List<User_Item> items { get; set; }
}
public class User_User2
{
public int uid { get; set; }
public string user_name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string location { get; set; }
public int is_supporter { get; set; }
public string url { get; set; }
public string bio { get; set; }
public string relationship { get; set; }
public string user_avatar { get; set; }
public int is_private { get; set; }
public List<object> contact { get; set; }
}
public class User_Beer2
{
public int bid { get; set; }
public string beer_name { get; set; }
public string beer_label { get; set; }
public string beer_style { get; set; }
public string beer_slug { get; set; }
public double beer_abv { get; set; }
public int beer_active { get; set; }
public bool has_had { get; set; }
public double auth_rating { get; set; }
public bool wish_list { get; set; }
}
public class User_Contact2
{
public string twitter { get; set; }
public string facebook { get; set; }
public string instagram { get; set; }
public string url { get; set; }
}
public class User_Location2
{
public string brewery_city { get; set; }
public string brewery_state { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Brewery2
{
public int brewery_id { get; set; }
public string brewery_name { get; set; }
public string brewery_slug { get; set; }
public string brewery_label { get; set; }
public string country_name { get; set; }
public User_Contact2 contact { get; set; }
public User_Location2 location { get; set; }
public int brewery_active { get; set; }
}
public class User_Comments
{
public int total_count { get; set; }
public int count { get; set; }
public List<object> items { get; set; }
}
public class User_User3
{
public int uid { get; set; }
public string user_name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string bio { get; set; }
public string location { get; set; }
public string user_avatar { get; set; }
public string account_type { get; set; }
public List<object> venue_details { get; set; }
public object brewery_details { get; set; }
public string user_link { get; set; }
}
public class User_Item3
{
public int uid { get; set; }
public User_User3 user { get; set; }
public int like_id { get; set; }
public bool like_owner { get; set; }
public string created_at { get; set; }
}
public class User_Toasts
{
public int total_count { get; set; }
public int count { get; set; }
public bool auth_toast { get; set; }
public List<User_Item3> items { get; set; }
}
public class User_Media
{
public int count { get; set; }
public List<object> items { get; set; }
}
public class User_Source
{
public string app_name { get; set; }
public string app_website { get; set; }
}
public class User_Badges
{
public bool retro_status { get; set; }
public int count { get; set; }
public List<Item4> items { get; set; }
}
public class Item4
{
public int badge_id { get; set; }
public int user_badge_id { get; set; }
public string badge_name { get; set; }
public string badge_description { get; set; }
public string created_at { get; set; }
public BadgeImage badge_image { get; set; }
}
public class BadgeImage
{
public string sm { get; set; }
public string md { get; set; }
public string lg { get; set; }
}
public class User_Item2
{
public int checkin_id { get; set; }
public string created_at { get; set; }
public string checkin_comment { get; set; }
public double rating_score { get; set; }
public User_User2 user { get; set; }
public User_Beer2 beer { get; set; }
public User_Brewery2 brewery { get; set; }
////public object venue { get; set; }
public User_Venue venue { get; set; }
public User_Comments comments { get; set; }
public User_Toasts toasts { get; set; }
public User_Media media { get; set; }
public User_Source source { get; set; }
public User_Badges badges { get; set; }
}
//public class User_Venue
//{
// public int venue_id { get; set; }
// public string venue_name { get; set; }
// public string venue_slug { get; set; }
// public string primary_category { get; set; }
// public string parent_category_id { get; set; }
// public User_Categories categories { get; set; }
// public User_Location3 location { get; set; }
// public User_Contact3 contact { get; set; }
// public User_Foursquare foursquare { get; set; }
// public User_VenueIcon venue_icon { get; set; }
// public bool is_verified { get; set; }
//}
//public class User_Categories
//{
// public int count { get; set; }
// public List<User_Item3> items { get; set; }
//}
//public class User_Foursquare
//{
// public string foursquare_id { get; set; }
// public string foursquare_url { get; set; }
//}
public class User_Pagination
{
public string since_url { get; set; }
public string next_url { get; set; }
public int max_id { get; set; }
}
public class User_Checkins
{
public int count { get; set; }
public List<User_Item2> items { get; set; }
public User_Pagination pagination { get; set; }
}
public class User_Photo
{
public string photo_img_sm { get; set; }
public string photo_img_md { get; set; }
public string photo_img_lg { get; set; }
public string photo_img_og { get; set; }
}
public class User_User4
{
public int uid { get; set; }
public string user_name { get; set; }
public string location { get; set; }
public string bio { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string user_avatar { get; set; }
public string account_type { get; set; }
public object url { get; set; }
}
public class User_Beer3
{
public int bid { get; set; }
public string beer_name { get; set; }
public string beer_label { get; set; }
public double beer_abv { get; set; }
public string beer_style { get; set; }
public string beer_description { get; set; }
public double auth_rating { get; set; }
public bool wish_list { get; set; }
}
public class User_Contact3
{
public string twitter { get; set; }
public string facebook { get; set; }
public string instagram { get; set; }
public string url { get; set; }
}
public class User_Location3
{
public string brewery_city { get; set; }
public string brewery_state { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Brewery3
{
public int brewery_id { get; set; }
public string brewery_name { get; set; }
public string brewery_slug { get; set; }
public string brewery_label { get; set; }
public string country_name { get; set; }
public User_Contact3 contact { get; set; }
public User_Location3 location { get; set; }
public int brewery_active { get; set; }
}
public class User_Item5
{
public string category_name { get; set; }
public string category_id { get; set; }
public bool is_primary { get; set; }
}
public class User_Categories
{
public int count { get; set; }
public List<User_Item5> items { get; set; }
}
public class User_Location4
{
public string venue_address { get; set; }
public string venue_city { get; set; }
public string venue_state { get; set; }
public string venue_country { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
public class User_Contact4
{
public string twitter { get; set; }
public string venue_url { get; set; }
}
public class User_Foursquare
{
public string foursquare_id { get; set; }
public string foursquare_url { get; set; }
}
public class User_VenueIcon
{
public string sm { get; set; }
public string md { get; set; }
public string lg { get; set; }
}
public class User_Venue
{
public int venue_id { get; set; }
public string venue_name { get; set; }
public string venue_slug { get; set; }
public string primary_category { get; set; }
public string parent_category_id { get; set; }
public User_Categories categories { get; set; }
public User_Location4 location { get; set; }
public User_Contact4 contact { get; set; }
public User_Foursquare foursquare { get; set; }
public User_VenueIcon venue_icon { get; set; }
public bool is_verified { get; set; }
}
public class User_Item4
{
public int photo_id { get; set; }
public User_Photo photo { get; set; }
public string created_at { get; set; }
public int checkin_id { get; set; }
public User_User4 user { get; set; }
public User_Beer3 beer { get; set; }
public User_Brewery3 brewery { get; set; }
public User_Venue venue { get; set; }
}
public class User_Media2
{
public int count { get; set; }
public List<User_Item4> items { get; set; }
}
public class User_Badge
{
public int badges_to_facebook { get; set; }
public int badges_to_twitter { get; set; }
}
public class User_Checkin
{
public int checkin_to_facebook { get; set; }
public int checkin_to_twitter { get; set; }
public int checkin_to_foursquare { get; set; }
}
public class User_Navigation
{
public int default_to_checkin { get; set; }
}
public class User_Settings
{
public User_Badge badge { get; set; }
public User_Checkin checkin { get; set; }
public User_Navigation navigation { get; set; }
public string email_address { get; set; }
}
public class AvailableColor
{
public string name { get; set; }
public string color { get; set; }
public List<int> values { get; set; }
}
public class MainItems
{
public string ItemName { get; set; }
public ObservableCollection<SubItems> SubItemsList { get; set; }
}
public class SubItems
{
public string SubItemName { get; set; }
}
public class IgnoreUnexpectedArraysConverter<T> : IgnoreUnexpectedArraysConverterBase
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
}
public class IgnoreUnexpectedArraysConverter : IgnoreUnexpectedArraysConverterBase
{
readonly IContractResolver resolver;
public IgnoreUnexpectedArraysConverter(IContractResolver resolver)
{
if (resolver == null)
throw new ArgumentNullException();
this.resolver = resolver;
}
public override bool CanConvert(Type objectType)
{
if (objectType.IsPrimitive || objectType == typeof(string))
return false;
return resolver.ResolveContract(objectType) is JsonObjectContract;
}
}
public abstract class IgnoreUnexpectedArraysConverterBase : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var contract = serializer.ContractResolver.ResolveContract(objectType);
if (!(contract is JsonObjectContract))
{
throw new JsonSerializationException(string.Format("{0} is not a JSON object", objectType));
}
do
{
if (reader.TokenType == JsonToken.Null)
return null;
else if (reader.TokenType == JsonToken.Comment)
continue;
else if (reader.TokenType == JsonToken.StartArray)
{
var array = JArray.Load(reader);
if (array.Count > 0)
throw new JsonSerializationException(string.Format("Array was not empty."));
return existingValue ?? contract.DefaultCreator();
}
else if (reader.TokenType == JsonToken.StartObject)
{
// Prevent infinite recursion by using Populate()
existingValue = existingValue ?? contract.DefaultCreator();
serializer.Populate(reader, existingValue);
return existingValue;
}
else
{
throw new JsonSerializationException(string.Format("Unexpected token {0}", reader.TokenType));
}
}
while (reader.Read());
throw new JsonSerializationException("Unexpected end of JSON.");
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
///// END OF CLASSES /////////
}
Thanks,
Rick
Since you have nesting what you can do is show the checkins.items[] in the listview like you are showing now and once the user selects an "item" from the checkins (i.e, an item from the listView), within the Tapped or SelectionChanged event of the list view get the selected item and show its list of "badge" items in a new listView.
private void lvRecenCheckins_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedCheckinItem = (sender as items).badges;
newListView.ItemSource = selectedCheckinItem.items;
}
Please note : this is based on the information that is provided in the question, actual class names might differ.
Hope this helps..! Do ask if you have any queries..
maybe you can have a look here: https://learn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension
I would try something like this:
<DataTemplate x:DataType="local:YourClass">
<Grid>
<TextBlock Text="{x:Bind GetFirstBadgeItemSmall(badges)}" />
</Grid>
</DataTemplate>
In your code behind, aka ViewModel you need to implement a new Method:
public string GetFirstBadgeItemSmall(IEnumerable<badge> badges)
{
return (badges?.items?[0].badge_image.small ?? string.empty);
}
Update
Maybe like this. I haven't tried it, just a guess:
<DataTemplate>
<Grid DataContext={Binding badges.items}>
<TextBlock Text="{Binding badge_image.small}" />
</Grid>
</DataTemplate>
I have the following json:
{
"13377": {
"id": 13377,
"orderId": 13377,
"executionStatus": "-1",
"comment": "",
"htmlComment": "",
"cycleId": -1,
"cycleName": "Ad hoc",
"versionId": 10001,
"versionName": "Version2",
"projectId": 10000,
"createdBy": "vm_admin",
"modifiedBy": "vm_admin",
"assignedTo": "user1",
"assignedToDisplay": "user1",
"assignedToUserName": "user1",
"assigneeType": "assignee",
"issueId": 10013,
"issueKey": "SAM-14",
"summary": "Test",
"label": "",
"component": "",
"projectKey": "SAM",
"folderId": 233,
"folderName": "testfolder"
}
}
I create the following classes using json2csharp and get:
public class __invalid_type__13377
{
public int id { get; set; }
public int orderId { get; set; }
public string executionStatus { get; set; }
public string comment { get; set; }
public string htmlComment { get; set; }
public int cycleId { get; set; }
public string cycleName { get; set; }
public int versionId { get; set; }
public string versionName { get; set; }
public int projectId { get; set; }
public string createdBy { get; set; }
public string modifiedBy { get; set; }
public string assignedTo { get; set; }
public string assignedToDisplay { get; set; }
public string assignedToUserName { get; set; }
public string assigneeType { get; set; }
public int issueId { get; set; }
public string issueKey { get; set; }
public string summary { get; set; }
public string label { get; set; }
public string component { get; set; }
public string projectKey { get; set; }
public int folderId { get; set; }
public string folderName { get; set; }
}
public class RootObject
{
public __invalid_type__13377 __invalid_name__13377 { get; set; }
}
When I deserialize in C# I receive no error but I get null?
Not sure how to approach this..any suggestions would be welcome.
thankyou.
Your Json object can be deserialized with an Dictionary. On this case, you can build your DataObject like you are doing:
public class Foo
{
public int id { get; set; }
public int orderId { get; set; }
...
}
And Deserialize to
Dictionary<string, Foo>
If you are using Newtonsoft:
var data = JsonConvert.DeserializeObject<Dictionary<string,Foo>(json);
You can use sometimes, when the type of object is unknown, the dynamic keyword:
var data = JsonConvert.DeserializeObject<dynamic>(json);
I have a WebApi returning the following JSON which I am trying to deserialize to the object below
JSON OBJECT
{
"results": [{
"id": 123456,
"fullName": "Foo Bar",
"localName": null,
"jobPosition": "ME",
"jobCompanyName": "EXTRA",
"jobLocationCountry": "United States of America",
"jobLocationCity": "San Francisco",
"jobCountrySubdivision": "California",
"boards": [],
"restrictionsIndicator": false,
"personRestriction": null,
"jobRestriction": null
}, {
"id": 789101,
"fullName": "Foo Bar",
"localName": null,
"jobPosition": null,
"jobCompanyName": "Unknown",
"jobLocationCountry": "Unknown",
"jobLocationCity": "Unknown",
"jobCountrySubdivision": "Unknown",
"boards": [{
"companyId": 667525,
"companyName": "FOO BAR COMPANY",
"companyOffLimits": null,
"restrictionCategoryId": null
}
],
"restrictionsIndicator": false,
"personRestriction": null,
"jobRestriction": null
}
],
"totalCount": 2,
"pageNumber": 1,
"resultsPerPage": 100
}
C# Classes
public class Rootobject
{
public Result[] results { get; set; }
public int totalCount { get; set; }
public int pageNumber { get; set; }
public int resultsPerPage { get; set; }
}
public class Result
{
public int id { get; set; }
public string fullName { get; set; }
public object localName { get; set; }
public string jobPosition { get; set; }
public string jobCompanyName { get; set; }
public string jobLocationCountry { get; set; }
public string jobLocationCity { get; set; }
public string jobCountrySubdivision { get; set; }
public Board[] boards { get; set; }
public bool restrictionsIndicator { get; set; }
public int? personRestriction { get; set; }
public int? jobRestriction { get; set; }
}
public class Board
{
public int companyId { get; set; }
public string companyName { get; set; }
public int? companyOffLimits { get; set; }
public object restrictionCategoryId { get; set; }
}
The DLL is a Portable Class Library which is .NET 4.5 and i have JSON.net(10.0.1) installed via nuget, but the portable library is connected to a xamarin IOS Project on a mac.
If the JSON being deserialized has no Boards it works out fine but if there is a Board then I receive the following message.
Unable to find a constructor to use for type Board. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'results[1].boards[0].companyId'
The Settings I am using are:
var settings = new Newtonsoft.Json.JsonSerializerSettings
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
};
I have tried the following ways to get it to serialize:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(_jsonString, settings);
var jobject = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(_jsonString, new Rootobject());
i have tried the following
Put in a default constructor
Naming all the parameters for the class in a constructor
Adding the Attribute to the constructor
Changing the Boards to a List
Taking out the Boards Property
but there is still no joy. It will not deserialize for me.
I think you have to modify this
public class Board
{
public int companyId { get; set; }
public string companyName { get; set; }
public int? companyOffLimits { get; set; }
public object restrictionCategoryId { get; set; }
**public Board(){}**
}
also in other classes
or also change
public Board[] boards { get; set; }
to
public List<Board> boards { get; set; }
Try....
I have an ID of a "Component" parent record that I need to retrieve all the "Attachment" child records. The grid I am using need fields returned an placed in "TheComponentAttachmentsJoinedTable" I am only able to retrieve one record. I have used the value of FirstorDefault. That is the only way it will accept the line of code without complaining about the IEnumerable to int. Could someone please explain what is incorrect?
public class Component
{
public int ID { get; set; }
public string ComponentCode { get; set; }
public string ComponentDescription { get; set; }
public double ComponentWeight { get; set; }
public double ComponentQuantity { get; set; }
public string LastModUser { get; set; }
public DateTime LastModDate { get; set; }
public virtual ICollection<Attachment> Attachments { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Element> Elements { get; set; }
}
public class Attachment
{
public int ID { get; set; }
public string AttachmentDescription { get; set; }
public string OriginalName { get; set; }
public string MimeType { get; set; }
public byte[] bytes { get; set; }
public string LastModUser { get; set; }
public DateTime LastModDate { get; set; }
//Navigation
public virtual ICollection<Element> Elements { get; set; }
public virtual ICollection<Component> Components { get; set; } //lt M-m
}
public class TheComponentAttachmentsJoinedTable
{
public int ComponentID { get; set; }
public int AttachmentID { get; set; }
public string OriginalName { get; set; }
}
public static List<TheComponentAttachmentsJoinedTable> ComponentAttachments_GetAllByComponentID(int ComponentID)
{
using (TheContext TheDB = new TheContext())
{
var r = (from x in TheDB.Component
.Where(x => x.ID == ComponentID)
.Include(x => x.Attachments)
select new TheComponentAttachmentsJoinedTable
{
ComponentID = x.ID,
AttachmentID = x.Attachments.Select(y => (y.ID)).FirstOrDefault(),
OriginalName = x.Attachments.Select(y => y.OriginalName).FirstOrDefault().ToString(),
}
);
return r.ToList();
}