I'm new on java/android:
I'm using this list of objects on wp7 and I want pass to android, how I do this:
My big object c#:
public class ListCountries
{
public List<CountriesRepresented> _countriesRepresented { get; set; }
public List<CountriesOrigin > _countriesOrigin { get; set; }
}
My others two objects in c#:
public class CountriesRepresented
{
public int CountryID { get; set; }
public string Designation { get; set; }
public string Symbol { get; set; }
public string NomDesignationISO { get; set; }
}
public class CountriesOrigin
{
public int CountryID { get; set; }
public string Designation { get; set; }
public string Symbol { get; set; }
public string NomDesignationISO { get; set; }
}
My java Deserializer:
public Object[] getListCountries()
{
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(Config.WS_PATH);
post.setHeader("content-type", "application/json; charset=UTF-8");
post.addHeader("Client-Application","3601cfde-e440-4a84-a2cc-a402f4c7bd14");
HttpResponse resp = httpClient.execute(post);
String respStr = EntityUtils.toString(resp.getEntity());
ListCountries _listCountries = new JSONDeserializer().deserialize(ListCountries .class, respStr);
return _listCountries;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
My big object in java:
public class ListCountries {
public List<CountriesRepresented> _CountriesRepresented;
public List<CountriesOrigin > _CountriesOrigin ;
public List<CountriesRepresented> getCountriesRepresented() {
return this._CountriesRepresented;
}
public List<CountriesOrigin > getCountriesOrigin() {
return this._CountriesOrigin ;
}
public void setCountriesRepresented (List<CountriesRepresented> CountriesRepresented) {
this._CountriesRepresented = CountriesRepresented;
}
public void setCountriesOrigin (List<CountriesOrigin > CountriesOrigin ) {
this._CountriesOrigin = CountriesOrigin ;
}
}
My service is on WebAPI and give me an correct answer example: `{"PaisesRepresentantes":[{"PaisID":4,"Designacao":"Alemanha","Sigla":"DEU","NomDesignacaoISO":"GERMANY"},{"PaisID":21,.......
your classes in Java should be something like,
public class ListCountries
{
public List<CountriesRepresented> _countriesRepresented; //Make it private if you want and then you can add getter setter function
public List<CountriesOrigin > _countriesOrigin;
}
public class CountriesRepresented
{
public int CountryID; //Make it private if you want and then you can add getter setter function
public String Designation;
public String Symbol;
public String NomDesignationISO;
}
public class CountriesOrigin
{
public int CountryID; //Make it private if you want and then you can add getter setter function
public String Designation;
public String Symbol;
public String NomDesignationISO;
}
The problem with your existing code is that you have declared variable as _CountriesRepresented rather it should be _countriesRepresented i.e. properties are case sensitive and those are mapped to variables declared in class and do remember to add a default constructor if you add any custom constructor to any of those classes
Related
I am invoking a method in my constructor like below.Is this the right way to do to set properties based on some validations.Please suggest.
public class Asset
{
public Asset(string id)
{
SetStorageId(id);
}
public string AssetId { get; set; }
public string UtilId { get; set; }
public string MappingId { get; set; }
public bool IsActive { get; set; }
private void SetStorageId(string id)
{
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
AssetId = id;
}
else
{
UtilId = id;
}
}
}
In my opinion your design should be like below,
You should abstract common items to base class and create specific class inheriting this,
and decide from client(consumer) which instance do you need and construct it
public class AssetBase
{
public string MappingId { get; set; }
public bool IsActive { get; set; }
}
public class Asset : AssetBase
{
public string AssetId { get; set; }
}
public class Util : AssetBase
{
public string UtilId { get; set; }
}
static void Main(string[] args)
{
string id = Console.ReadLine();
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
Asset asset = new Asset();
asset.AssetId = id;
}
else
{
Util util = new Util();
util.UtilId = id;
}
}
simply try this
public class Asset
{
private string id;
public string AssetId { get; set; }
public string UtilId { get; set; }
public string Id
{
set
{
if (Regex.Match(value, "^[A-Z][a-zA-Z]*$").Success)
{
this.id = value;
}
else
{
UtilId = value;
}
}
get
{
return id;
}
}
}
When you create a property in c#, a private variable is created for that property on compile time. When you try to set the Id property in the code above the Id you pass goes into the value keyword and you can perform your validations on the value keyword and set your property accordingly.
No need to complicate your code with set methods, constructors or deriving classes
or you can even use data annotations which is a more elegant way https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx#Properties
using System.ComponentModel.DataAnnotations;
public class Asset
{
[RegularExpression("^[A-Z][a-zA-Z]*$")]
public string Id { get; set; }
}
It's not wrong. It can possibly grow to be a little confusing. Maybe you can make it clearer by moving the bod of SetStorageId to the constructor. Perhaps there is no need to complicate with subclassing, relative to other code within the project.
I'm looking for the best approach of working with different types identically.
I have a web service that goes to specific resource, makes some research and returns an object WebResult, that contains all information about completed operations.
And now I'd like to build a set of different metrics, that will describe all received results. These metrics should provide
different types of data
easy way to collect it
possibility to deserialize it.
Example 1
First I've created separate classes for different metrics
public abstract class AbstractStatistic
{
public string Url { get; set; }
public string ExceptionMessage { get; set; }
public abstract void FillAllMetrics(WebResult result);
}
public class Resource1Statistic : AbstractStatistic
{
public string Title { get; set; }
public string[] Table1_Header { get; set; }
public int Table1_RowCount { get; set; }
public string[] Table2_Header { get; set; }
public int Table2_RowCount { get; set; }
public override void FillAllMetrics(WebResult result)
{
this.Url = result.url;
this.Title = result.data["title"];
this.Table1_Header = result.data["table1.header"].ToObject<string[]>();
//...
}
}
It works, but I'd like to make it in more standard way. One of the reason is that in this approach I have to create separate web form for each metrics.
Example 2
Second working example is universal but redundant: create an abstraction of any datatype
public abstract class AbstractStatistic
{
public string Url { get; set; }
public string Exception { get; set; }
public Dictionary<string, Metric> Metrics { get ;set;}
public abstract void FillAllMetrics(WebResult webResult);
}
public class Metric // Specific class for data
{
public string StringValue { get; set; }
public int? IntegerValue { get; set; }
public string[] ArrayValue { get; set; }
public DateTime? DateTimeValue { get; set; }
}
public class Resource1Statistic : AbstractStatistic
{
public override void FillAllMetrics(WebResult result)
{
this.Metrics.Add("title",
new Metric() { StringValue = result.data["title"].ToString() });
this.Metrics.Add("Table1 Header",
new Metric() { ArrayValue = result.data["table1.header"].ToObject<string[]>() });
//...
}
It works, but I'm sure there is more elegant solution. I don't like to take all these null values in json.
Examples 3
Generic solution (regarding to Adwaenyth)
public abstract class AbstractStatistic
{
public string Url { get; set; }
public string Exception { get; set; }
public List<AbstractMetric> Metrics { get ;set;}
public abstract void FillAllMetrics(WebResult webResult);
}
public abstract class AbstractMetric{}
public class Metric<T> : AbstractMetric
{
public string Name { get; set; }
public T Value { get; set; }
public string Type { get; private set; }
public Metric()
{
this.Type = typeof(T).ToString();
}
}
public class Resource1Statistic : AbstractStatistic
{
public override void FillAllMetrics(WebResult result)
{
this.Metrics.Add(new Metric<string>()
{ Name = "title",
Value = result.data["title"].ToString() });
this.Metrics.Add(new Metric<string[]>()
{ Name = "Table1 Header",
Value = result.data["table1.header"].ToObject<string[]>() });
//...
}
This solution looks nice, but I have to write custom deserializer.
What do you think, is there some good pattern that fits to my task? Or what's the best approach?
I have two classes with some similar fields, some different, and a form that utilizes two different objects depending on what mode it's in (insert/edit).
Instead of using two different objects and if statements checking the form mode, I'd like to have one struct to be hydrated with either of the two objects fields so I can manipulate one object through the page life-cycle. Then separated the struct back to its respective object for insert/updating the DB.
Example of classes:
public partial class SomeClass
{
public Int32 B {get;set;}
public String C {get;set;}
public Boolean D {get;set;}
}
public class SomeOtherClass
{
public Int32 A {get;set;}
public Int32 B {get;set;}
public String C {get;set;}
}
Update with Solution Example:
public interface IInsertable
{
string SharedName { get; set; }
string SharedID { get; set; }
string editedFieldValue { get; set; }
long GetSuperSecreteInfo();
}
internal class InsertableImplementation : IInsertable
{
public string SharedName { get; set; }
public string SharedID { get; set; }
public string editedFieldValue { get; set; }
public long GetSuperSecreteInfo()
{
return -1;
}
}
public interface IUpdateable
{
string SharedName { get; set; }
string SharedID { get; set; }
string updatedFieldValue { get; set; }
Guid GenerateStevesMagicGuid();
}
internal class UpdateableImplementation : IUpdateable
{
public string SharedName { get; set; }
public string SharedID { get; set; }
public string updatedFieldValue { get; set; }
public Guid GenerateStevesMagicGuid()
{
return new Guid();
}
}
public static class WonderTwinFactory
{
public static WonderTwins GenerateWonderTwin(IUpdateable updateable, IInsertable insertable)
{
var wt = new WonderTwins();
// who will win?
wt.SharedID = updateable.SharedID;
wt.SharedID = insertable.SharedID;
// you decide?
wt.SharedName = updateable.SharedName;
wt.editedFieldValue = "stuff";
return wt;
}
}
public class WonderTwins : IInsertable, IUpdateable
{
public string SharedName { get; set; }
public string SharedID { get; set; }
public string editedFieldValue { get; set; }
public long GetSuperSecreteInfo()
{
return 1;
}
public string updatedFieldValue { get; set; }
public Guid GenerateStevesMagicGuid()
{
return new Guid();
}
}
class Program
{
static void Main(string[] args)
{
IUpdateable updateable = new UpdateableImplementation();
IInsertable insertable = new InsertableImplementation();
WonderTwins dualImplementatin = WonderTwinFactory.GenerateWonderTwin(updateable, insertable);
IUpdateable newUpdateable = dualImplementatin as IUpdateable;
IInsertable newInsertable = dualImplementatin as IInsertable;
}
}
Have both classes implement an interface that defines the operations common to each, including both the fields that are shared (assuming the view needs to access them) and also a method to actually perform the operation that they represent (insert/edit).
Other way of doing such things is using C# dynamic object and assign properties directly. It may help to avoid any new type or interface and directly utilizing new dynamic object any time, as much as required.
var newObject = new {
objectOfClass1 = x.prop1,
objectOfClass2 = x.prop2
}
I build a rest service which output are json. I using Newtonsoft.Json.
This is my class.
public class DownloadPDA
{
public List<FRUTE> lsRute { get; set; }
public List<FCUSTMST> lsCustomer { get; set; }
public List<FMASTER> lsMaster { get; set; }
public List<FNOTEC> lsNotec { get; set; }
public List<FINFO> lsInfo { get; set; }
public List<FBRAND> lsBrand { get; set; }
public List<FKPL> lsKpl { get; set; }
}
but when I test my rest service my result are:
{"downloadDataResult":"{"lsBrand":[{}],"lsCustomer":[{},{},{}],"lsInfo":[],"lsKpl":null,"lsMaster":[{},{},{},{},{}],"lsNotec":[],"lsRute":[{},{},{}]}"}
it not show the data in list. I know something is wrong. Can anybody help?
This one of my collection class
public class FRUTE
{
private String norute;
private String custno;
private String flag;
private String st_visit;
private float amount;
private int jmlvisit;
public FRUTE() { }
public void getData(DCTRTDTO dto) {
this.norute = dto.NOROUT;
this.custno = dto.NOCUST;
this.flag = dto.FLAG;
this.st_visit = "not yet";
this.amount = 10;
this.jmlvisit = 1;
}
public static List<FRUTE> getList(List<DCTRTDTO> lsRute)
{
List<FRUTE> ls = new List<FRUTE>();
FRUTE info = new FRUTE();
foreach (DCTRTDTO dto in lsRute)
{
info.getData(dto);
ls.Add(info);
}
return ls;
}
}
Your FRUTE class doesn't have public properties that are required for Json serialization.
Encapsulate you private fields and all will work as expected.
public class FRUTE
{
private String norute;
private String custno;
public string Norute
{
get { return norute; }
set { norute = value; }
}
public string Custno
{
get { return custno; }
set { custno = value; }
}
//...
}
I have a business model which consists of a parent/child relationship (Identifier/IdentifierValue) and also some snapshot classes which look the same (IdentifierSnapshot/IdentifierValueSnapshot).
I am trying to create an extension method which will work on an enumeration of either Identifier or IdentifierSnapshot, but I just can't work out what to put in the extension method where I have inserted the XXX placeholder.
//Interfaces
public interface IIdentifier<TIdentifierValue>
where TIdentifierValue : IIdentifierValue
{
string Code { get; }
IEnumerable<TIdentifierValue> GetValues();
}
public interface IIdentifierValue
{
string Code { get; }
string Value { get; }
}
//Main classes
public class Identifier : IIdentifier<IdentifierValue>
{
public string Code { get; set; }
public IEnumerable<IdentifierValue> GetValues();
}
public class IdentifierValue : IIdentifierValue
{
public string Code { get; set; }
public string Value { get; set; }
}
//Snapshots
public class IdentifierSnapshot : IIdentifier<IdentifierValueSnapshot>
{
public string Code { get; set; }
public IEnumerable<IdentifierValueSnapshot> GetValues();
}
public class IdentifierValueSnapshot : IIdentifierValue
{
public string Code { get; set; }
public string Value { get; set; }
}
public static IdentifierExtensions
{
public static IEnumerable<XXX> ByCode<XXX>(this IEnumerable<XXX> instance, string code)
{
return instance.Where(x => string.Compare(code, x.Code, true) == 0);
}
}
I think this would do it:
public static IEnumerable<T> ByCode<T,Z>(this IEnumerable<T> instance, string code)
where T:IIdentifier<Z>
where Z:IIdentifierValue