Burzhuin
asked on
REST API Returns seems nothing
Now I have no error. But something in my logic cause the function to run without result.
So here are two functions:
public string CreateAttribute(String ProdID, int counter)
{
bool fireAgain = false;
String strProdID = ProdID;
String strFund = "";
String strAppeal = "";
String strPackage = "";
String strreturn = "";
int cnt = counter;
// Build WC API complete URL
string wcApiCompleteUrl = Variables.WCAPIBaseUrl + "products/" + strProdID + "/?" + "consumer_key=" + Variables.WCAPIConsumerKey + "&consumer_secret=" + Variables.WCAPIConsumerSec ret;
// Just some kind of debug output :-)
ComponentMetaData.FireInfo rmation(10 , "Start - URL", String.Format("The following URL has been used: {0}", wcApiCompleteUrl), "", 0, fireAgain);
try
{
//Call getWebServiceResult to return our WorkGroupMetric array
WCProduct[] wcProductOutput = GetRestServiceResult1(wcAp iCompleteU rl);
//MessageBox.Show("CreateA ttribute Function within try!");
////For each group of metrics output records
foreach (var wcProducts in wcProductOutput)
{
MessageBox.Show("CreateAtt ribute Function is in first foreach loop!");
if (wcProducts.Attributes.Len gth == 0)
{
MessageBox.Show("It is IF Statement in CreateAttribute Function");
strFund = "NONE";
strAppeal = "NONE";
strPackage = "NONE";
}
else
{
MessageBox.Show("It is ELSE Statement in CreateAttribute Function");
foreach (var wcAttribute in wcProducts.Attributes)
{
MessageBox.Show("We are inside foreach loop");
if (wcAttribute.NameID == "Re-fund-member")
{
strFund = wcAttribute.options;
}
if (wcAttribute.NameID == "Re-appeal-code")
{
strAppeal = wcAttribute.options;
}
if (wcAttribute.NameID == "Re-package-code")
{
strPackage = wcAttribute.options;
}
}
}
}
if (cnt == 1)
{
strreturn = strFund;
}
if (cnt == 2)
{
strreturn = strAppeal;
}
if (cnt == 3)
{
strreturn = strPackage;
}
}
catch (Exception e)
{
FailComponent(e.ToString() );
return "";
}
return strreturn;
}
private WCProduct[] GetRestServiceResult1(stri ng wUrl)
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest .Create(wU rl);
if (Variables.UseStandardProx y)
{
httpWReq.Proxy.Credentials = CredentialCache.DefaultNet workCreden tials;
httpWReq.PreAuthenticate = true;
}
HttpWebResponse httpWResp = (HttpWebResponse)httpWReq. GetRespons e();
WCProduct[] jsonResponse = null;
try
{
//Test the connection
if (httpWResp.StatusCode == HttpStatusCode.OK)
{
//Stream responseStream = httpWResp.GetResponseStrea m();
string jsonString = null;
//Set jsonString using a stream reader
using (StreamReader reader = new StreamReader(httpWResp.Get ResponseSt ream(), System.Text.Encoding.UTF8) )
{
jsonString = reader.ReadToEnd();// Replace("\\", "");
reader.Close();
}
//Deserialize our JSON
//JavaScriptSerializer sr = new JavaScriptSerializer();
//JSON string comes in with a leading and trailing " that need to be removed for parsing to work correctly
//The JSON here is serialized weird, normally you would not need this trim
//jsonResponse = sr.Deserialize<WCOrder[]>( jsonString .Trim('"') );
WCProducts jsonRoot = DeserializeJSon<WCProducts >(jsonStri ng);
jsonResponse = jsonRoot.Product;
}
//Output connection error message
else
{
FailComponent(httpWResp.St atusCode.T oString()) ;
}
}
//Output JSON parsing error
catch (Exception e)
{
FailComponent(e.ToString() );
}
return jsonResponse;
}
Here are two lanes I am suspicious about:
WCProduct[] wcProductOutput = GetRestServiceResult1(wcAp iCompleteU rl);
foreach (var wcProducts in wcProductOutput)
wcProductOutput must contain one entry. We are looking for particular Product and call it by Product ID. But somehow foreach never triggered. I am lost in doubts. Can somebody tell me, what is wrong in my logic here?
So here are two functions:
public string CreateAttribute(String ProdID, int counter)
{
bool fireAgain = false;
String strProdID = ProdID;
String strFund = "";
String strAppeal = "";
String strPackage = "";
String strreturn = "";
int cnt = counter;
// Build WC API complete URL
string wcApiCompleteUrl = Variables.WCAPIBaseUrl + "products/" + strProdID + "/?" + "consumer_key=" + Variables.WCAPIConsumerKey
// Just some kind of debug output :-)
ComponentMetaData.FireInfo
try
{
//Call getWebServiceResult to return our WorkGroupMetric array
WCProduct[] wcProductOutput = GetRestServiceResult1(wcAp
//MessageBox.Show("CreateA
////For each group of metrics output records
foreach (var wcProducts in wcProductOutput)
{
MessageBox.Show("CreateAtt
if (wcProducts.Attributes.Len
{
MessageBox.Show("It is IF Statement in CreateAttribute Function");
strFund = "NONE";
strAppeal = "NONE";
strPackage = "NONE";
}
else
{
MessageBox.Show("It is ELSE Statement in CreateAttribute Function");
foreach (var wcAttribute in wcProducts.Attributes)
{
MessageBox.Show("We are inside foreach loop");
if (wcAttribute.NameID == "Re-fund-member")
{
strFund = wcAttribute.options;
}
if (wcAttribute.NameID == "Re-appeal-code")
{
strAppeal = wcAttribute.options;
}
if (wcAttribute.NameID == "Re-package-code")
{
strPackage = wcAttribute.options;
}
}
}
}
if (cnt == 1)
{
strreturn = strFund;
}
if (cnt == 2)
{
strreturn = strAppeal;
}
if (cnt == 3)
{
strreturn = strPackage;
}
}
catch (Exception e)
{
FailComponent(e.ToString()
return "";
}
return strreturn;
}
private WCProduct[] GetRestServiceResult1(stri
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest
if (Variables.UseStandardProx
{
httpWReq.Proxy.Credentials
httpWReq.PreAuthenticate = true;
}
HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.
WCProduct[] jsonResponse = null;
try
{
//Test the connection
if (httpWResp.StatusCode == HttpStatusCode.OK)
{
//Stream responseStream = httpWResp.GetResponseStrea
string jsonString = null;
//Set jsonString using a stream reader
using (StreamReader reader = new StreamReader(httpWResp.Get
{
jsonString = reader.ReadToEnd();// Replace("\\", "");
reader.Close();
}
//Deserialize our JSON
//JavaScriptSerializer sr = new JavaScriptSerializer();
//JSON string comes in with a leading and trailing " that need to be removed for parsing to work correctly
//The JSON here is serialized weird, normally you would not need this trim
//jsonResponse = sr.Deserialize<WCOrder[]>(
WCProducts jsonRoot = DeserializeJSon<WCProducts
jsonResponse = jsonRoot.Product;
}
//Output connection error message
else
{
FailComponent(httpWResp.St
}
}
//Output JSON parsing error
catch (Exception e)
{
FailComponent(e.ToString()
}
return jsonResponse;
}
Here are two lanes I am suspicious about:
WCProduct[] wcProductOutput = GetRestServiceResult1(wcAp
foreach (var wcProducts in wcProductOutput)
wcProductOutput must contain one entry. We are looking for particular Product and call it by Product ID. But somehow foreach never triggered. I am lost in doubts. Can somebody tell me, what is wrong in my logic here?
If foreach is not triggered, it sounds like your service doesn't return anything. Have you checked that? Did you get any other exception or error?
ASKER
Yes, of course. I used REST Console and run API here is the result I got:
{
"product": {
"title": "Individual Ticket (Aspire)",
"id": 29861,
"created_at": "2015-01-05T21:06:42Z",
"updated_at": "2015-03-25T13:30:15Z",
"type": "simple",
.......................
"attributes": [{
"name": "Re-event-code",
"position": "0",
"visible": false,
"variation": false,
"options": ["1504ASPIREGALA"]
}, {
"name": "Re-appeal-code",
"position": "1",
"visible": false,
"variation": false,
"options": ["1504EVSPXXAG"]
}, {
"name": "Re-fund-number",
"position": "2",
"visible": false,
"variation": false,
"options": ["027604"]
}, {
"name": "Re-benefit-value",
"position": "3",
"visible": false,
"variation": false,
"options": ["200"]
}, {
"name": "Re-package-code",
"position": "4",
"visible": false,
"variation": false,
"options": ["1504EVSPXXRT"]
}],
..........................
I need to read attributes.
{
"product": {
"title": "Individual Ticket (Aspire)",
"id": 29861,
"created_at": "2015-01-05T21:06:42Z",
"updated_at": "2015-03-25T13:30:15Z",
"type": "simple",
.......................
"attributes": [{
"name": "Re-event-code",
"position": "0",
"visible": false,
"variation": false,
"options": ["1504ASPIREGALA"]
}, {
"name": "Re-appeal-code",
"position": "1",
"visible": false,
"variation": false,
"options": ["1504EVSPXXAG"]
}, {
"name": "Re-fund-number",
"position": "2",
"visible": false,
"variation": false,
"options": ["027604"]
}, {
"name": "Re-benefit-value",
"position": "3",
"visible": false,
"variation": false,
"options": ["200"]
}, {
"name": "Re-package-code",
"position": "4",
"visible": false,
"variation": false,
"options": ["1504EVSPXXRT"]
}],
..........................
I need to read attributes.
ASKER
I need to retrieve attributes of the Product. Here is why I have to call Product using this URL:
https://apibuild.giving.massgeneral.org/wc-api/v2/products/29861/?consumer_key=KEY&consume r_secret=K EY
My variable Variables.WCAPIBaseUrl contains this string:
https://apibuild.giving.massgeneral.org/wc-api/v2/.
So the array must contain at least one member. Unfortunately attributes are not set for each product. So I have to check if attributes have any data. For clarity sake I am using product # 29861 for each order since I know that its atributes are all set. I am really confused.
https://apibuild.giving.massgeneral.org/wc-api/v2/products/29861/?consumer_key=KEY&consume
My variable Variables.WCAPIBaseUrl contains this string:
https://apibuild.giving.massgeneral.org/wc-api/v2/.
So the array must contain at least one member. Unfortunately attributes are not set for each product. So I have to check if attributes have any data. For clarity sake I am using product # 29861 for each order since I know that its atributes are all set. I am really confused.
ASKER
I received no errors or warnings when I compiled and run the package.
Looks like it deserialization issue, since I don't know how your WCProducts/DeserializeJSon are implemented, but I doubt the issue lies in below lines:
Try to debug and see what you get in jsonRoot.Product.
As you described the response you got from Console test, "product" is not an array of Product, but just a single Product object. So maybe it is cause, because your GetRestServiceResult1 tries to return an array of Products (WCProduct[]). Did you also try to deserialize the response to WCProduct[] in your Console test program?
WCProducts jsonRoot = DeserializeJSon<WCProducts>(jsonString);
jsonResponse = jsonRoot.Product;
Try to debug and see what you get in jsonRoot.Product.
As you described the response you got from Console test, "product" is not an array of Product, but just a single Product object. So maybe it is cause, because your GetRestServiceResult1 tries to return an array of Products (WCProduct[]). Did you also try to deserialize the response to WCProduct[] in your Console test program?
I think the cause is in your response data.
Response should be:
The square brackets are missing to indicate that "product" is an array.
Try below sample code to see the differences:
Response should be:
{ "product": [{ "title": ..... attributes: [{...}] }] }
The square brackets are missing to indicate that "product" is an array.
Try below sample code to see the differences:
public class WCProducts
{
public List<WCProduct> Product { get; set; }
}
public class WCProduct
{
public string Title { get; set; }
public int Id { get; set; }
public DateTime Created_at { get; set; }
public DateTime Updated_at { get; set; }
public string Type { get; set; }
public List<ProductAttribute> Attributes { get; set; }
}
public class ProductAttribute
{
public string Name { get; set; }
public string Position { get; set; }
public bool Visible { get; set; }
public bool Variation { get; set; }
public List<string> Options { get; set; }
}
static void Main(string[] args)
{
string jsonString = "{ \"product\": { \"title\": \"Individual Ticket (Aspire)\", \"id\": 29861,\"created_at\": \"2015-01-05T21:06:42Z\", \"updated_at\": \"2015-03-25T13:30:15Z\", \"type\": \"simple\", \"attributes\": [{ \"name\": \"Re-event-code\", \"position\": \"0\", \"visible\": false, \"variation\": false, \"options\": [\"1504ASPIREGALA\"] }] } }";
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
WCProducts jsonRoot = jsSerializer.Deserialize<WCProducts>(jsonString);
Console.WriteLine("Number of Products in invalid JSON response: {0}", jsonRoot.Product.Count);
jsonString = "{ \"product\": [{ \"title\": \"Individual Ticket (Aspire)\", \"id\": 29861,\"created_at\": \"2015-01-05T21:06:42Z\", \"updated_at\": \"2015-03-25T13:30:15Z\", \"type\": \"simple\", \"attributes\": [{ \"name\": \"Re-event-code\", \"position\": \"0\", \"visible\": false, \"variation\": false, \"options\": [\"1504ASPIREGALA\"] }] }] }";
jsonRoot = jsSerializer.Deserialize<WCProducts>(jsonString);
Console.WriteLine("Number of Products in valid JSON response: {0}", jsonRoot.Product.Count);
}
ASKER
Here is how I declare my classes:
[DataContract]
class WCProducts
{
[DataMember(Name = "product")]
public WCProduct[] Product { get; set; }
}
[DataContract]
class WCProduct
{
[DataMember(Name = "id")]
public string ProductID { get; set; }
[DataMember(Name = "sku")]
public string Productsku { get; set; }
[DataMember(Name = "title")]
public string ProductName { get; set; }
[DataMember(Name = "attributes")]
public WCAttribute[] ProductAttributes { get; set; }
}
[DataContract]
class WCAttribute
{
[DataMember(Name = "name")]
public string NameID { get; set; }
[DataMember(Name = "position")]
public string Position { get; set; }
[DataMember(Name = "visible")]
public string Visible { get; set; }
[DataMember(Name = "variation")]
public string Variation { get; set; }
[DataMember(Name = "options")]
public string Options { get; set; }
}
I do not see the difference.
[DataContract]
class WCProducts
{
[DataMember(Name = "product")]
public WCProduct[] Product { get; set; }
}
[DataContract]
class WCProduct
{
[DataMember(Name = "id")]
public string ProductID { get; set; }
[DataMember(Name = "sku")]
public string Productsku { get; set; }
[DataMember(Name = "title")]
public string ProductName { get; set; }
[DataMember(Name = "attributes")]
public WCAttribute[] ProductAttributes { get; set; }
}
[DataContract]
class WCAttribute
{
[DataMember(Name = "name")]
public string NameID { get; set; }
[DataMember(Name = "position")]
public string Position { get; set; }
[DataMember(Name = "visible")]
public string Visible { get; set; }
[DataMember(Name = "variation")]
public string Variation { get; set; }
[DataMember(Name = "options")]
public string Options { get; set; }
}
I do not see the difference.
ASKER
I noticed that result of execution the following line:
WCProduct[] wcProductOutput = GetRestServiceResult1(wcAp iCompleteU rl);
is empty array. How would you recommend to proceed? Can you tell me please what exact in this Function should I replace:
private WCProduct[] GetRestServiceResult1(stri ng wUrl)
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest .Create(wU rl);
if (Variables.UseStandardProx y)
{
httpWReq.Proxy.Credentials = CredentialCache.DefaultNet workCreden tials;
httpWReq.PreAuthenticate = true;
}
HttpWebResponse httpWResp = (HttpWebResponse)httpWReq. GetRespons e();
WCProduct[] jsonResponse = null;
try
{
//Test the connection
if (httpWResp.StatusCode == HttpStatusCode.OK)
{
//Stream responseStream = httpWResp.GetResponseStrea m();
string jsonString = null;
//Set jsonString using a stream reader
using (StreamReader reader = new StreamReader(httpWResp.Get ResponseSt ream(), System.Text.Encoding.UTF8) )
{
jsonString = reader.ReadToEnd();// Replace("\\", "");
reader.Close();
}
WCProducts jsonRoot = DeserializeJSon<WCProducts >(jsonStri ng);
jsonResponse = jsonRoot.Product;
}
//Output connection error message
else
{
FailComponent(httpWResp.St atusCode.T oString()) ;
}
}
//Output JSON parsing error
catch (Exception e)
{
FailComponent(e.ToString() );
}
return jsonResponse;
}
WCProduct[] wcProductOutput = GetRestServiceResult1(wcAp
is empty array. How would you recommend to proceed? Can you tell me please what exact in this Function should I replace:
private WCProduct[] GetRestServiceResult1(stri
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest
if (Variables.UseStandardProx
{
httpWReq.Proxy.Credentials
httpWReq.PreAuthenticate = true;
}
HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.
WCProduct[] jsonResponse = null;
try
{
//Test the connection
if (httpWResp.StatusCode == HttpStatusCode.OK)
{
//Stream responseStream = httpWResp.GetResponseStrea
string jsonString = null;
//Set jsonString using a stream reader
using (StreamReader reader = new StreamReader(httpWResp.Get
{
jsonString = reader.ReadToEnd();// Replace("\\", "");
reader.Close();
}
WCProducts jsonRoot = DeserializeJSon<WCProducts
jsonResponse = jsonRoot.Product;
}
//Output connection error message
else
{
FailComponent(httpWResp.St
}
}
//Output JSON parsing error
catch (Exception e)
{
FailComponent(e.ToString()
}
return jsonResponse;
}
Your problem is in the response data, not the client-code to deserialize the data.
Your current response is:
In this response, "product" is NOT an array, it is a single object. Therefore when deserializing to an array of WCProduct[] (declared in WCProducts class), deserializer will create an empty array.
There are 2 options for you to correct this:
1. Correct your REST service to return valid response data, so that "product" is an array as below:
2. Re-define WCProducts class so that it Product property is just a single WCProduct object as below:
and then, in your GetRestServiceResult1() function, only return a single WCProduct instead of an array
But not that, option #2 only returns a single WCProduct object. It might not be your intention, so you should consider option #1.
Your current response is:
{
"product": {
"title": "Individual Ticket (Aspire)",
"id": 29861,
"created_at": "2015-01-05T21:06:42Z",
"updated_at": "2015-03-25T13:30:15Z",
"type": "simple",
.......................
"attributes": [{
"name": "Re-event-code",
"position": "0",
"visible": false,
"variation": false,
"options": ["1504ASPIREGALA"]
}...]
}
}
In this response, "product" is NOT an array, it is a single object. Therefore when deserializing to an array of WCProduct[] (declared in WCProducts class), deserializer will create an empty array.
There are 2 options for you to correct this:
1. Correct your REST service to return valid response data, so that "product" is an array as below:
{
"product": [ // the square bracket indicates an array
{
"title": "Individual Ticket (Aspire)",
"id": 29861,
"created_at": "2015-01-05T21:06:42Z",
"updated_at": "2015-03-25T13:30:15Z",
"type": "simple",
.......................
"attributes": [{
"name": "Re-event-code",
"position": "0",
"visible": false,
"variation": false,
"options": ["1504ASPIREGALA"]
}...]
}
] // end of array of WCProduct objects
}
2. Re-define WCProducts class so that it Product property is just a single WCProduct object as below:
[DataContract]
class WCProducts
{
[DataMember(Name = "product")]
public WCProduct Product { get; set; }
}
and then, in your GetRestServiceResult1() function, only return a single WCProduct instead of an array
function WCProduct GetRestServiceResult1(...)
{
...
WCProduct jsonResponse = null;
...
WCProducts jsonRoot = DeserializeJSon<WCProducts>(jsonString);
jsonResponse = jsonRoot.Product;
...
return jsonResponse;
}
But not that, option #2 only returns a single WCProduct object. It might not be your intention, so you should consider option #1.
ASKER
WebService in my case returns:
"{\"product\":{\"title\":\ "Individua l Ticket (Aspire)\",\"id\":29861,\" created_at \":\"2015- 01-05T21:0 6:42Z\",\" updated_at \":\"2015- 03-30T14:2 4:18Z\",\" type\":\"s imple\",\" status\":\ "publish\" ,\"downloa dable\":fa lse,\"virt ual\":true ,\"permali nk\":\"https:\\/\\/apibuild.giving.massgeneral.org\\/product\\/corporate-individual-ticket-aspire\\/\",\ "sku\":\"2 015-aspire -single-co rporate-ti cket\",\"p rice\":\"5 00.00\",\" regular_pr ice\":\"50 0.00\",\"s ale_price\ ":null,\"p rice_html\ ":\"<span class=\\\"woocommerce-pric e-before\\ \"> <\\/span><span class=\\\"amount\\\">$ 500.00<\\/ span><span class=\\\"woocommerce-pric e-after\\\ "> <\\/span>\",\"taxable\":fa lse,\"tax_ status\":\ "taxable\" ,\"tax_cla ss\":\"\", \"managing _stock\":f alse,\"sto ck_quantit y\":0,\"in _stock\":t rue,\"back orders_all owed\":fal se,\"backo rdered\":f alse,\"sol d_individu ally\":fal se,\"purch aseable\": true,\"fea tured\":fa lse,\"visi ble\":true ,\"catalog _visibilit y\":\"cata log\",\"on _sale\":fa lse,\"weig ht\":null, \"dimensio ns\":{\"le ngth\":\"\ ",\"width\ ":\"\",\"h eight\":\" \",\"unit\ ":\"in\"}, \"shipping _required\ ":false,\" shipping_t axable\":t rue,\"ship ping_class \":\"\",\" shipping_c lass_id\": null,\"des cription\" :\"<ul>\\n <li>One ticket to\\u00a0Aspire 2015<\\/li>\\n<li>Listing in the annual Mass General Donor Report<\\/li>\\n<\\/ul>\\n \",\"short _descripti on\":\"<ul >\\n<li>On e ticket to\\u00a0Aspire 2015<\\/li>\\n<li>Listing in the annual Mass General Donor Report<\\/li>\\n<\\/ul>\\n \",\"revie ws_allowed \":false,\ "average_r ating\":\" 0.00\",\"r ating_coun t\":0,\"re lated_ids\ ":[32051,3 2132,32134 ,32135,321 36],\"upse ll_ids\":[ ],\"cross_ sell_ids\" :[],\"pare nt_id\":0, \"categori es\":[\"As pire\"],\" tags\":[], \"images\" :[{\"id\": 0,\"create d_at\":\"2 015-03-30T 18:50:49Z\ ",\"update d_at\":\"2 015-03-30T 18:50:49Z\ ",\"src\": \"\\/plugi ns\\/wooco mmerce\\/a ssets\\/im ages\\/pla ceholder.p ng\",\"tit le\":\"Pla ceholder\" ,\"alt\":\ "Placehold er\",\"pos ition\":0} ],\"featur ed_src\":f alse,\"att ributes\": [{\"name\" :\"Re-even t-code\",\ "position\ ":\"0\",\" visible\": false,\"va riation\": false,\"op tions\":[\ "1504ASPIR EGALA\"]}, {\"name\": \"Re-appea l-code\",\ "position\ ":\"1\",\" visible\": false,\"va riation\": false,\"op tions\":[\ "1504EVSPX XAG\"]},{\ "name\":\" Re-fund-nu mber\",\"p osition\": \"3\",\"vi sible\":fa lse,\"vari ation\":fa lse,\"opti ons\":[\"0 27604\"]}, {\"name\": \"Re-benef it-value\" ,\"positio n\":\"4\", \"visible\ ":false,\" variation\ ":false,\" options\": [\"200\"]} ],\"downlo ads\":[],\ "download_ limit\":0, \"download _expiry\": 0,\"downlo ad_type\": \"\",\"pur chase_note \":\"<p>$3 00.00 of the purchase of each ticket is tax-deductible to the full extent of the law<\\/p>\\n\",\"total_sal es\":67,\" variations \":[],\"pa rent\":[]} }" string
If this is not an array, I do not know what it is.
"{\"product\":{\"title\":\
If this is not an array, I do not know what it is.
ASKER
In my case I can replace "}}" by "}]}". But unfortunately I cannot use the same trick for ":{" since I have two occurences. And I would really appreciate if you advise me how to change my REST API request so it would return array. I really appreciate you help and I am really grateful.
Please see JSON array syntax described here: https://www.json.com/json-array.
For your information: try to parse your jsonString at this site: http://json.parser.online.fr/.
For your information: try to parse your jsonString at this site: http://json.parser.online.fr/.
You can't change that by the request because above jsonString is formatted by your REST API service.
As long as jsonString response is { "product": { "title": "Product name",... } }, then your WCProducts.Product will never be able to be deserialized properly as WCProduct[].
Response jsonString must be something like { "product": [ {"title": "Product 1",...}, {"title": "Product 2",...} ] } in order to get WCProducts be deserialized properly.
If you just simply want your GetRestServiceResult1 to return WCProduct[], you need to make 2 changes:
As long as jsonString response is { "product": { "title": "Product name",... } }, then your WCProducts.Product will never be able to be deserialized properly as WCProduct[].
Response jsonString must be something like { "product": [ {"title": "Product 1",...}, {"title": "Product 2",...} ] } in order to get WCProducts be deserialized properly.
If you just simply want your GetRestServiceResult1 to return WCProduct[], you need to make 2 changes:
Change definition of WCProducts class:
[DataContract] class WCProducts { [DataMember(Name = "product")] public WCProduct Product { get; set; } }
[DataContract] class WCProducts { [DataMember(Name = "product")] public WCProduct Product { get; set; } }
Modify your function GetRestServiceResult1
function WCProduct GetRestServiceResult1(...) { ... WCProducts jsonRoot = DeserializeJSon<WCProducts>(jsonString); jsonResponse = new WCProduct[] { jsonRoot.Product }; ... }
function WCProduct GetRestServiceResult1(...) { ... WCProducts jsonRoot = DeserializeJSon<WCProducts>(jsonString); jsonResponse = new WCProduct[] { jsonRoot.Product }; ... }
ASKER
I did as you advised and got an error: "Error 2 Cannot implicitly convert type 'WCProduct[]' to 'WCProduct'" in this lane: jsonResponse = new WCProduct[] { jsonRoot.Product };
It seems that you declared jsonResponse as WCProduct, it should be WCProduct[] as your original code:
WCProduct[] jsonResponse = null;
ASKER
Is there any other way?
ASKER
I used exactly as you wrote. When I used:
WCProduct jsonResponse = null;
Compiler generated two errors. Now only one: "Cannot implicitly convert type 'WCProduct[]' to 'WCProduct' " in return:
return jsonResponse;
WCProduct jsonResponse = null;
Compiler generated two errors. Now only one: "Cannot implicitly convert type 'WCProduct[]' to 'WCProduct' " in return:
return jsonResponse;
ASKER
Is there any way to jump to attributes?
To return WCProduct[], your function should be:
To get WCAttribute[] from the same response, your function should be:
function WCProduct[] GetRestServiceResult1(...)
{
...
WCProduct[] jsonResponse = null;
...
WCProducts jsonRoot = DeserializeJSon<WCProducts>(jsonString);
jsonResponse = new WCProduct[] { jsonRoot.Product };
...
return jsonResponse;
}
To get WCAttribute[] from the same response, your function should be:
function WCAttribute[] GetRestServiceResult1(...)
{
...
WCAttribute[] jsonResponse = null;
...
WCProducts jsonRoot = DeserializeJSon<WCProducts>(jsonString);
jsonResponse = jsonRoot.Product.ProductAttributes;
...
return jsonResponse;
}
ASKER
I got no compiler errors but when I run it I got for each call two errors.
1. [Error Getting Data From Webservice!] Error: System.Runtime.Serializati on.Seriali zationExce ption: There was an error deserializing the object of type WCProducts. Encountered unexpected character ':'. ---> System.Xml.XmlException: Encountered unexpected character ':'.
at System.Xml.XmlExceptionHel per.ThrowX mlExceptio n(XmlDicti onaryReade r reader, XmlException exception)
at System.Runtime.Serializati on.Json.Xm lJsonReade r.Read()
at System.Xml.XmlBaseReader.S kip()
at System.Runtime.Serializati on.XmlRead erDelegato r.Skip()
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.SkipUn knownEleme nt(XmlRead erDelegato r xmlReader)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Handle MemberNotF ound(XmlRe aderDelega tor xmlReader, ExtensionDataObject extensionData, Int32 memberIndex)
at System.Runtime.Serializati on.Json.Xm lObjectSer ializerRea dContextCo mplexJson. GetJsonMem berIndex(X mlReaderDe legator xmlReader, XmlDictionaryString[] memberNames, Int32 memberIndex, ExtensionDataObject extensionData)
at ReadWCProductFromJson(XmlR eaderDeleg ator , XmlObjectSerializerReadCon textComple xJson , XmlDictionaryString , XmlDictionaryString[] )
at System.Runtime.Serializati on.Json.Js onClassDat aContract. ReadJsonVa lueCore(Xm lReaderDel egator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Js onDataCont ract.ReadJ sonValue(X mlReaderDe legator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadJ sonValue(D ataContrac t contract, XmlReaderDelegator reader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Xm lObjectSer ializerRea dContextCo mplexJson. ReadDataCo ntractValu e(DataCont ract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont extComplex .InternalD eserialize (XmlReader Delegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadWCProductsFromJson(Xml ReaderDele gator , XmlObjectSerializerReadCon textComple xJson , XmlDictionaryString , XmlDictionaryString[] )
at System.Runtime.Serializati on.Json.Js onClassDat aContract. ReadJsonVa lueCore(Xm lReaderDel egator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Js onDataCont ract.ReadJ sonValue(X mlReaderDe legator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadJ sonValue(D ataContrac t contract, XmlReaderDelegator reader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Xm lObjectSer ializerRea dContextCo mplexJson. ReadDataCo ntractValu e(DataCont ract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont extComplex .InternalD eserialize (XmlReader Delegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.Inter nalReadObj ect(XmlRea derDelegat or xmlReader, Boolean verifyObjectName)
at System.Runtime.Serializati on.XmlObje ctSerializ er.Interna lReadObjec t(XmlReade rDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serializati on.XmlObje ctSerializ er.ReadObj ectHandleE xceptions( XmlReaderD elegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
--- End of inner exception stack trace ---
at System.Runtime.Serializati on.XmlObje ctSerializ er.ReadObj ectHandleE xceptions( XmlReaderD elegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serializati on.XmlObje ctSerializ er.ReadObj ectHandleE xceptions( XmlReaderD elegator reader, Boolean verifyObjectName)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadO bject(XmlD ictionaryR eader reader)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadO bject(Stre am stream)
at ScriptMain.DeserializeJSon [T](String jsonString) in c:\Users\rk688\AppData\Loc al\Temp\Vs ta\b535f4d 68b0f423cb 79f6e34670 2f8a0\main .cs:line 562
at ScriptMain.GetRestServiceR esult1(Str ing wUrl) in c:\Users\rk688\AppData\Loc al\Temp\Vs ta\b535f4d 68b0f423cb 79f6e34670 2f8a0\main .cs:line 530
2. [Error Getting Data From Webservice!] Error: System.NullReferenceExcept ion: Object reference not set to an instance of an object.
at ScriptMain.CreateAttribute (String ProdID, Int32 counter) in c:\Users\rk688\AppData\Loc al\Temp\Vs ta\b535f4d 68b0f423cb 79f6e34670 2f8a0\main .cs:line 384
Should I remove columns ":" from jsonString?
1. [Error Getting Data From Webservice!] Error: System.Runtime.Serializati
at System.Xml.XmlExceptionHel
at System.Runtime.Serializati
at System.Xml.XmlBaseReader.S
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at ReadWCProductFromJson(XmlR
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at ReadWCProductsFromJson(Xml
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
--- End of inner exception stack trace ---
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at ScriptMain.DeserializeJSon
at ScriptMain.GetRestServiceR
2. [Error Getting Data From Webservice!] Error: System.NullReferenceExcept
at ScriptMain.CreateAttribute
Should I remove columns ":" from jsonString?
ASKER
I run second time and I got different error:
[Error Getting Data From Webservice!] Error: System.Runtime.Serializati on.Seriali zationExce ption: There was an error deserializing the object of type WCProducts. End element 'options' from namespace '' expected. Found element 'item' from namespace ''. ---> System.Xml.XmlException: End element 'options' from namespace '' expected. Found element 'item' from namespace ''.
at System.Xml.XmlExceptionHel per.ThrowX mlExceptio n(XmlDicti onaryReade r reader, String res, String arg1, String arg2, String arg3)
at System.Xml.XmlExceptionHel per.ThrowE ndElementE xpected(Xm lDictionar yReader reader, String localName, String ns)
at System.Xml.XmlBaseReader.R eadEndElem ent()
at System.Xml.XmlBaseReader.R eadElement ContentAsS tring()
at System.Runtime.Serializati on.XmlRead erDelegato r.ReadElem entContent AsString()
at ReadWCAttributeFromJson(Xm lReaderDel egator , XmlObjectSerializerReadCon textComple xJson , XmlDictionaryString , XmlDictionaryString[] )
at System.Runtime.Serializati on.Json.Js onClassDat aContract. ReadJsonVa lueCore(Xm lReaderDel egator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Js onDataCont ract.ReadJ sonValue(X mlReaderDe legator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadJ sonValue(D ataContrac t contract, XmlReaderDelegator reader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Xm lObjectSer ializerRea dContextCo mplexJson. ReadDataCo ntractValu e(DataCont ract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont extComplex .InternalD eserialize (XmlReader Delegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadArrayOfWCAttributeFrom Json(XmlRe aderDelega tor , XmlObjectSerializerReadCon textComple xJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
at System.Runtime.Serializati on.Json.Js onCollecti onDataCont ract.ReadJ sonValueCo re(XmlRead erDelegato r jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Js onDataCont ract.ReadJ sonValue(X mlReaderDe legator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadJ sonValue(D ataContrac t contract, XmlReaderDelegator reader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Xm lObjectSer ializerRea dContextCo mplexJson. ReadDataCo ntractValu e(DataCont ract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont extComplex .InternalD eserialize (XmlReader Delegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadWCProductFromJson(XmlR eaderDeleg ator , XmlObjectSerializerReadCon textComple xJson , XmlDictionaryString , XmlDictionaryString[] )
at System.Runtime.Serializati on.Json.Js onClassDat aContract. ReadJsonVa lueCore(Xm lReaderDel egator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Js onDataCont ract.ReadJ sonValue(X mlReaderDe legator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadJ sonValue(D ataContrac t contract, XmlReaderDelegator reader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Xm lObjectSer ializerRea dContextCo mplexJson. ReadDataCo ntractValu e(DataCont ract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont extComplex .InternalD eserialize (XmlReader Delegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
at ReadWCProductsFromJson(Xml ReaderDele gator , XmlObjectSerializerReadCon textComple xJson , XmlDictionaryString , XmlDictionaryString[] )
at System.Runtime.Serializati on.Json.Js onClassDat aContract. ReadJsonVa lueCore(Xm lReaderDel egator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Js onDataCont ract.ReadJ sonValue(X mlReaderDe legator jsonReader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadJ sonValue(D ataContrac t contract, XmlReaderDelegator reader, XmlObjectSerializerReadCon textComple xJson context)
at System.Runtime.Serializati on.Json.Xm lObjectSer ializerRea dContextCo mplexJson. ReadDataCo ntractValu e(DataCont ract dataContract, XmlReaderDelegator reader)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or reader, String name, String ns, Type declaredType, DataContract& dataContract)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont ext.Intern alDeserial ize(XmlRea derDelegat or xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
at System.Runtime.Serializati on.XmlObje ctSerializ erReadCont extComplex .InternalD eserialize (XmlReader Delegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.Inter nalReadObj ect(XmlRea derDelegat or xmlReader, Boolean verifyObjectName)
at System.Runtime.Serializati on.XmlObje ctSerializ er.Interna lReadObjec t(XmlReade rDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serializati on.XmlObje ctSerializ er.ReadObj ectHandleE xceptions( XmlReaderD elegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
--- End of inner exception stack trace ---
at System.Runtime.Serializati on.XmlObje ctSerializ er.ReadObj ectHandleE xceptions( XmlReaderD elegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serializati on.XmlObje ctSerializ er.ReadObj ectHandleE xceptions( XmlReaderD elegator reader, Boolean verifyObjectName)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadO bject(XmlD ictionaryR eader reader)
at System.Runtime.Serializati on.Json.Da taContract JsonSerial izer.ReadO bject(Stre am stream)
at ScriptMain.DeserializeJSon [T](String jsonString) in c:\Users\rk688\AppData\Loc al\Temp\Vs ta\56a31aa 1c0b2490ab a5b143011b e11a5\main .cs:line 562
at ScriptMain.GetRestServiceR esult1(Str ing wUrl) in c:\Users\rk688\AppData\Loc al\Temp\Vs ta\56a31aa 1c0b2490ab a5b143011b e11a5\main .cs:line 530
[Error Getting Data From Webservice!] Error: System.Runtime.Serializati
at System.Xml.XmlExceptionHel
at System.Xml.XmlExceptionHel
at System.Xml.XmlBaseReader.R
at System.Xml.XmlBaseReader.R
at System.Runtime.Serializati
at ReadWCAttributeFromJson(Xm
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at ReadArrayOfWCAttributeFrom
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at ReadWCProductFromJson(XmlR
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at ReadWCProductsFromJson(Xml
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
--- End of inner exception stack trace ---
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at System.Runtime.Serializati
at ScriptMain.DeserializeJSon
at ScriptMain.GetRestServiceR
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Dear Duy Pham,
Your last advise worked!!!!!!!!!!!!!!!!!! Where can I go and express my gratitude and appreciation. You spent so much time helping me. Thank you!!!!!
Your last advise worked!!!!!!!!!!!!!!!!!! Where can I go and express my gratitude and appreciation. You spent so much time helping me. Thank you!!!!!
ASKER
Sorry, I missed feedback window. Is there any way I can get back and type my appreciation? Thank you, dear Duy, one more time. I do appreciate it.
You are welcome, and great to hear that it helps :).