Trouble with List (UWP) - c#

I writing app for UWP platform.
I using Binding in code.
Here code for my ViewModel:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Milano.Annotations;
using WooCommerceNET;
using WooCommerceNET.WooCommerce;
using Newtonsoft.Json;
namespace Milano.Classes
{
public class InWorkViewModel: INotifyPropertyChanged
{
private List<LineItem> productList;
public List<LineItem> ProductList
{
get { return productList; }
set { productList = value; OnPropertyChanged(); }
}
private List<RootObject> ordersList;
public List<RootObject> OrdersList
{
get { return ordersList; }
set { ordersList = value; OnPropertyChanged(); }
}
private RootObject ordersChange;
public RootObject OrdersChange
{
get { return ordersChange; }
set { ordersChange = value; OnPropertyChanged(); }
}
private LineItem ordersChange2;
public LineItem OrdersChange2
{
get { return ordersChange2; }
set { ordersChange2 = value;OnPropertyChanged(); }
}
public InWorkViewModel()
{
Inwork_down();
// var interval = 100000;
//UpdateWithImterwal(interval);
}
/* private async void UpdateWithImterwal(int interval)
{
// OrdersList.Clear();
Inwork_down();
await Task.Delay(interval).ContinueWith(_ => UpdateWithImterwal(interval));
}*/
public async void Inwork_down()
{
RestAPI rest = new RestAPI("http://simplegames.com.ua/wp-json/wc/v1/", "ck_9d64c027d2c5f81b8bed3342eeccc6d337be813d", "cs_60697b1e6cbdeb8d62d19e0765e339f8e3334754");
WCObject wc = new WCObject(rest);
//Get all products
var orders = await wc.GetOrders(new Dictionary<string, string>() {
{ "per_page", "100" }, { "status","processing"} }); // Dodelat filtr dlaya teh chto v rabote
string products = orders.ToFormattedJsonString();
Debug.WriteLine(products);
List<RootObject> rootObjectData = JsonConvert.DeserializeObject<List<RootObject>>(products);
OrdersList = new List<RootObject>(rootObjectData);
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Billing
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
public string email { get; set; }
public string phone { get; set; }
}
public class Shipping
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postcode { get; set; }
public string country { get; set; }
}
public class LineItem
{
public int id { get; set; }
public string name { get; set; }
public string sku { get; set; }
public int product_id { get; set; }
public int variation_id { get; set; }
public int quantity { get; set; }
public string tax_class { get; set; }
public double price { get; set; }
public double subtotal { get; set; }
public double subtotal_tax { get; set; }
public double total { get; set; }
public double total_tax { get; set; }
public List<object> taxes { get; set; }
public List<object> meta { get; set; }
}
public class ShippingLine
{
public int id { get; set; }
public string method_title { get; set; }
public string method_id { get; set; }
public double total { get; set; }
public double total_tax { get; set; }
public List<object> taxes { get; set; }
}
public class RootObject
{
public int id { get; set; }
public int parent_id { get; set; }
public string status { get; set; }
public string order_key { get; set; }
public string currency { get; set; }
public string version { get; set; }
public bool prices_include_tax { get; set; }
public string date_created { get; set; }
public string date_modified { get; set; }
public int customer_id { get; set; }
public double discount_total { get; set; }
public double discount_tax { get; set; }
public double shipping_total { get; set; }
public double shipping_tax { get; set; }
public double cart_tax { get; set; }
public double total { get; set; }
public double total_tax { get; set; }
public Billing billing { get; set; }
public Shipping shipping { get; set; }
public string payment_method { get; set; }
public string payment_method_title { get; set; }
public string transaction_id { get; set; }
public string customer_ip_address { get; set; }
public string customer_user_agent { get; set; }
public string created_via { get; set; }
public string customer_note { get; set; }
public string date_completed { get; set; }
public string date_paid { get; set; }
public string cart_hash { get; set; }
public List<LineItem> line_items { get; set; }
public List<object> tax_lines { get; set; }
public List<ShippingLine> shipping_lines { get; set; }
public List<object> fee_lines { get; set; }
public List<object> coupon_lines { get; set; }
}
Where is my problem.
As you see I have this public List<LineItem> line_items { get; set; } in classes. I need to take this list from RootObject and make Binding for values in it like I do for rootObject.
So what is logic of View in app. I BinŠ² some data to Left panel, when I tap element on left panel, I make visible right panel, where I bind properties from public RootObject OrdersChange.
Here is some screens:
How I can do this?

If I understand correctly, you want bind 2 classes to one view. If so, I can suggest 2 ways:
1) Create base class for this 2 classes.
class BaseClass { }
class RootObject: BaseClass { }
class LineItem : BaseClass { }
class MainViewModel
{
public List<LineItem> ProductList { get; set; }
public List<RootObject> OrdersList { get; set; }
public BaseClass LeftListViewSelectedItem { get; set; }
}
2) Or you can set return type of property LeftListViewSelectedItem to object. For binding it's no matter what you return.

Related

Accessing Nested Collection View JSON data

I have a nested JSON data to be accessed. The data is structured into nested data which i want to have into one.
I modeled the JSON response into c# model classes
public class Customer1
{
public string district { get; set; }
public string feeder { get; set; }
public string feeder_code { get; set; }
public string transformer { get; set; }
public string dss_code { get; set; }
public string database_match { get; set; }
public string accountnumber { get; set; }
public string meterno { get; set; }
public TransactionalDetails transactional_details { get; set; }
}
public class Customer2
{
public string accountNumber { get; set; }
public string meterNumber { get; set; }
public string phoneNumber { get; set; }
public int billedAmount { get; set; }
public object billedDate { get; set; }
public string lastPayDate { get; set; }
public Lastpayment lastpayment { get; set; }
}
public class Lastpayment
{
public string transactionRef { get; set; }
public int units { get; set; }
public string transactionDate { get; set; }
public string transactionId { get; set; }
public int transactionBookId { get; set; }
public int amountPaid { get; set; }
public int mscPaid { get; set; }
public string invoiceNumber { get; set; }
}
public class Queryresult
{
public string responseMessage { get; set; }
public Customer1 customer1 { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
public class Result
{
public ObservableCollection<Customer1> Customer1 { get; set; }
public int row_count { get; set; }
}
public class Root
{
public bool error { get; set; }
public Result result { get; set; }
}
public class TransactionalDetails
{
public Queryresult queryresult { get; set; }
public bool status { get; set; }
}
I also created the following code to access the data using the root.
var data = JsonConvert.DeserializeObject<root>(readTask);
ObservableCollection<Customer1> innerData2 = data.result.Customer1;
My challenge is that i want to have Customer1, Customer2 and last payment data merged into a single collection view.
with what i have done, i can only access customer1 data. how can i access all into a single collection?

Cannot Deserialize JSON Object type requires a JSON array (e.g. [1,2,3]) to deserialize correctly

I'm having some issues handling a JSON array, Here is what I've tried. I have tried also using <List<jsonResponse.RootObect> and get the same result.
I'm using JSON.NET
C#:
jsonResponse.RootObject deserializedResponse = JsonConvert.DeserializeObject<jsonResponse.RootObject>(Globals.jsonResponse);
CLASS:
namespace QuantumView
{
[JsonObjectAttribute]
class jsonResponse
{
public class TransactionReference
{
public string CustomerContext { get; set; }
}
public class Response
{
public TransactionReference TransactionReference { get; set; }
public string ResponseStatusCode { get; set; }
public string ResponseStatusDescription { get; set; }
}
public class SubscriptionStatus
{
public string Code { get; set; }
public string Description { get; set; }
}
public class StatusType
{
public string Code { get; set; }
public string Description { get; set; }
}
public class Address
{
public string AddressLine1 { get; set; }
public string City { get; set; }
public string StateProvinceCode { get; set; }
public string PostalCode { get; set; }
public string CountryCode { get; set; }
}
public class Shipper
{
public string Name { get; set; }
public string ShipperNumber { get; set; }
public Address Address { get; set; }
}
public class Address2
{
public string ConsigneeName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string StateProvinceCode { get; set; }
public string PostalCode { get; set; }
public string CountryCode { get; set; }
}
public class ShipTo
{
public string AttentionName { get; set; }
public string PhoneNumber { get; set; }
public Address2 Address { get; set; }
}
public class ReferenceNumber
{
public string Number { get; set; }
public string Value { get; set; }
}
public class Service
{
public string Code { get; set; }
}
public class Activity
{
public string Date { get; set; }
public string Time { get; set; }
}
public class Dimensions
{
public string Length { get; set; }
public string Width { get; set; }
public string Height { get; set; }
}
public class UnitOfMeasurement
{
public string Code { get; set; }
}
public class DimensionalWeight
{
public UnitOfMeasurement UnitOfMeasurement { get; set; }
public string Weight { get; set; }
}
public class PackageWeight
{
public string Weight { get; set; }
}
public class ReferenceNumber2
{
public string Number { get; set; }
public string Value { get; set; }
}
public class PackageServiceOptions
{
public string COD { get; set; }
}
[JsonArray]
public class Package
{
public Activity Activity { get; set; }
public Dimensions Dimensions { get; set; }
public DimensionalWeight DimensionalWeight { get; set; }
public PackageWeight PackageWeight { get; set; }
public string TrackingNumber { get; set; }
public List<ReferenceNumber2> ReferenceNumber { get; set; }
public PackageServiceOptions PackageServiceOptions { get; set; }
}
public class BillToAccount
{
public string Option { get; set; }
public string Number { get; set; }
}
[JsonArray]
public class Manifest
{
public Shipper Shipper { get; set; }
public ShipTo ShipTo { get; set; }
public List<ReferenceNumber> ReferenceNumber { get; set; }
public Service Service { get; set; }
public string PickupDate { get; set; }
public string ScheduledDeliveryDate { get; set; }
public string ScheduledDeliveryTime { get; set; }
public string DocumentsOnly { get; set; }
public Package Package { get; set; }
public string ShipmentChargeType { get; set; }
public BillToAccount BillToAccount { get; set; }
}
public class SubscriptionFile
{
public string FileName { get; set; }
public StatusType StatusType { get; set; }
public List<Manifest> Manifest { get; set; }
public object Origin { get; set; }
}
This is where I'm getting the error..
[JsonArray]
public class SubscriptionEvents
{
public string Name { get; set; }
public string Number { get; set; }
public SubscriptionStatus SubscriptionStatus { get; set; }
public List<SubscriptionFile> SubscriptionFile { get; set; }
}
public class QuantumViewEvents
{
public string SubscriberID { get; set; }
public SubscriptionEvents SubscriptionEvents { get; set; }
}
public class QuantumViewResponse
{
public Response Response { get; set; }
public QuantumViewEvents QuantumViewEvents { get; set; }
public string Bookmark { get; set; }
}
public class RootObject
{
public QuantumViewResponse QuantumViewResponse { get; set; }
}
}
}
The problem was with my class not having the correct properties, it also turns out that the UPS api doesn't send a static type response and it can be different each time.. requiring a new class to deserialize into. I have not found a way to make the class flexible

Null value in json object

I made a code for deserialize this JSON
First of all, I've created a class:
public class Self
{
public string href { get; set; }
}
public class Soccerseason
{
public string href { get; set; }
}
public class HomeTeam
{
public string href { get; set; }
}
public class AwayTeam
{
public string href { get; set; }
}
public class Links
{
public Self self { get; set; }
public Soccerseason soccerseason { get; set; }
public HomeTeam homeTeam { get; set; }
public AwayTeam awayTeam { get; set; }
}
public class Result
{
public int goalsHomeTeam { get; set; }
public int goalsAwayTeam { get; set; }
}
public class LastHomeWinHomeTeam
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class LastWinHomeTeam
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class LastAwayWinAwayTeam
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class LastWinAwayTeam
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class Head2head
{
public int count { get; set; }
public string timeFrameStart { get; set; }
public string timeFrameEnd { get; set; }
public int homeTeamWins { get; set; }
public int awayTeamWins { get; set; }
public int draws { get; set; }
public LastHomeWinHomeTeam lastHomeWinHomeTeam { get; set; }
public LastWinHomeTeam lastWinHomeTeam { get; set; }
public LastAwayWinAwayTeam lastAwayWinAwayTeam { get; set; }
public LastWinAwayTeam lastWinAwayTeam { get; set; }
public List<Fixture> fixtures { get; set; }
}
public class Fixture
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class RootObject
{
public List<Fixture> fixture { get; set; }
public Head2head head2head { get; set; }
}
So I made a code for parsing a request, and return a responseText:
string responseText = Parser.Request(link); //Parser is the class that perform HttpRequest
so far no problem.
I've declarated the object for deserialize the responseText returned:
var obj = JsonConvert.DeserializeObject<Fixtures.RootObject>(responseText);
and next I do the foreach:
foreach (var fixture in obj.fixture)
{do stuff..}
but in obj.fixture I get null and I don't know why. Because all JSON is deserialized correcly. What am I doing wrong?
The key in the JSON is "fixtures" - it needs to match the property name of your class exactly. Change
public List<Fixture> fixture { get; set; }
to
public List<Fixture> fixtures { get; set; }
Alternatively, you can use the JsonProperty attribute:
[JsonProperty("fixtures")]
public List<Fixture> fixture { get; set; }

Put JSON items into a WPF GRID in C#

How to put the items in a JSON string in a WPF grid?
{
"success":"true",
"response":{
"Page":1,
"PageFirst":1,
"PageLast":1,
"PageRecordFirst":1,
"PageRecordLast":2147483647,
"PageSize":2147483647,
"RecordCount":2,
"ResultSet":[
{
"CompanyId":1,
"CompanyName":"Focus",
"ComputedProjectProgressAll":39.000000,
"ComputedProjectProgressCurrent":39.000000,
"ComputedProjectProgressExpected":86.00,
"ComputedTaskCountAll":434,
"ComputedTaskCountCurrent":354,
"CreateDate":"\/Date(1421947846600-0800)\/",
"CreateUserId":1,
"CreateUserName":"MobiCloud Admin",
"CustomerId":1,
"CustomerName":"MobiCloud",
"Description":"Obra 001",
"Id":7,
"IsActive":true,
"ModifyDate":"\/Date(1421947846600-0800)\/",
"ModifyUserId":1,
"ModifyUserName":"MobiCloud Admin",
"Name":"Obra Desenv 001",
"Status":0
},
{
"CompanyId":1,
"CompanyName":"Focus",
"ComputedProjectProgressAll":69.000000,
"ComputedProjectProgressCurrent":69.000000,
"ComputedProjectProgressExpected":100.00,
"ComputedTaskCountAll":199,
"ComputedTaskCountCurrent":199,
"CreateDate":"\/Date(1422298868660-0800)\/",
"CreateUserId":1,
"CreateUserName":"MobiCloud Admin",
"CustomerId":1,
"CustomerName":"MobiCloud",
"Description":"sadasdsad",
"Id":8,
"IsActive":true,
"ModifyDate":"\/Date(1422298868660-0800)\/",
"ModifyUserId":1,
"ModifyUserName":"MobiCloud Admin",
"Name":"Obra Desenv 002",
"Status":0
}
]
}
}
First of all you need to create a c# class equivalent to JSON. use http://json2csharp.com/ to create c# class. Then you need to deserialize your JSON string use JSON.NET from http://json.codeplex.com/. Now you have got all the things setup. Now you can assing these data into WPF controls. I have assigned the response resultset into one datagrid. Refer the below code.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
string str = File.ReadAllText("1.txt");
RootObject deserializedObject = JsonConvert.DeserializeObject<RootObject>(str);
dgr.ItemsSource = deserializedObject.response.ResultSet;
}
}
public class ResultSet
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public double ComputedProjectProgressAll { get; set; }
public double ComputedProjectProgressCurrent { get; set; }
public double ComputedProjectProgressExpected { get; set; }
public int ComputedTaskCountAll { get; set; }
public int ComputedTaskCountCurrent { get; set; }
public DateTime CreateDate { get; set; }
public int CreateUserId { get; set; }
public string CreateUserName { get; set; }
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string Description { get; set; }
public int Id { get; set; }
public bool IsActive { get; set; }
public DateTime ModifyDate { get; set; }
public int ModifyUserId { get; set; }
public string ModifyUserName { get; set; }
public string Name { get; set; }
public int Status { get; set; }
}
public class Response
{
public int Page { get; set; }
public int PageFirst { get; set; }
public int PageLast { get; set; }
public int PageRecordFirst { get; set; }
public long PageRecordLast { get; set; }
public long PageSize { get; set; }
public int RecordCount { get; set; }
public List<ResultSet> ResultSet { get; set; }
}
public class RootObject
{
public string success { get; set; }
public Response response { get; set; }
}
<Grid>
<DataGrid x:Name="dgr"/>
</Grid>

JSON Serializer C#

I am developing online aircraft sales system.
But I have a problem..
A URL address have:
string urlFlightSearch = "https://api.iati.com/rest/flightSearch/" + ado.iatiKod + "";
A have class "iati.cs" in codes
public class iati
{
public class flightSearch
{
public string fromAirport { get; set; }
public bool allinFromCity { get; set; }
public string toAirport { get; set; }
public string fromDate { get; set; }
public string returnDate { get; set; }
public string adult { get; set; }
public string currency { get; set; }
}
public class Leg
{
public string flightNo { get; set; }
public string aircraft { get; set; }
public string operatorCode { get; set; }
public string operatorName { get; set; }
public string departureAirport { get; set; }
public string departureTime { get; set; }
public string departureAirportName { get; set; }
public string departureCityName { get; set; }
public string arrivalAirport { get; set; }
public string arrivalTime { get; set; }
public string arrivalAirportName { get; set; }
public string arrivalCityName { get; set; }
}
public class Detail
{
public double price { get; set; }
public double serviceFee { get; set; }
public double tax { get; set; }
public int suplement { get; set; }
}
public class Fare
{
public double totalSingleAdultFare { get; set; }
public string currency { get; set; }
public string type { get; set; }
public List<string> segmentNames { get; set; }
public int freeSeatCount { get; set; }
public Detail detail { get; set; }
}
public class Flight
{
public string id { get; set; }
public string providerKey { get; set; }
public string pricingType { get; set; }
public int packageId { get; set; }
public List<Leg> legs { get; set; }
public List<Fare> fares { get; set; }
public int segmentCount { get; set; }
public int baggage { get; set; }
public int flightTimeHour { get; set; }
public int flightTimeMinute { get; set; }
public int layoverTime { get; set; }
public bool hasCip { get; set; }
public bool canBook { get; set; }
public bool canRezerve { get; set; }
public bool dayCross { get; set; }
public bool returnFlight { get; set; }
}
public class Result
{
public string searchId { get; set; }
public List<Flight> flights { get; set; }
}
public class RootObject
{
public Result result { get; set; }
}
}
And posting...
WebClient wc = new WebClient();
var serializer = new JavaScriptSerializer();
iati.flightSearch search = new iati.flightSearch()
{
fromAirport = "IST",
allinFromCity = true,
toAirport = "AYT",
fromDate = "2013-12-23",
returnDate = "2013-12-30",
adult = "1",
currency = "EUR"
};
var serializedResult = serializer.Serialize(search);
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
string result = wc.UploadString(urlFlightSearch, serializedResult);
iati.Flight flight = serializer.Deserialize<iati.Flight>(result);
But the result returned is always coming up empty.
Regards.
use Newtonsoft
JsonConvert.DeserializeObject(result);

Categories

Resources