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.WCAPIConsumerSecret;
        // Just some kind of debug output :-)
        ComponentMetaData.FireInformation(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(wcApiCompleteUrl);
            //MessageBox.Show("CreateAttribute Function within try!");
            ////For each group of metrics output records
            foreach (var wcProducts in wcProductOutput)
            {
                MessageBox.Show("CreateAttribute Function is in first foreach loop!");
                if (wcProducts.Attributes.Length == 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(string wUrl)
    {

        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);

        if (Variables.UseStandardProxy)
        {
            httpWReq.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
            httpWReq.PreAuthenticate = true;
        }
        HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
        WCProduct[] jsonResponse = null;

        try
        {
            //Test the connection
            if (httpWResp.StatusCode == HttpStatusCode.OK)
            {

                //Stream responseStream = httpWResp.GetResponseStream();
                string jsonString = null;

                //Set jsonString using a stream reader
                using (StreamReader reader = new StreamReader(httpWResp.GetResponseStream(), 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>(jsonString);
                jsonResponse = jsonRoot.Product;
            }
            //Output connection error message
            else
            {
                FailComponent(httpWResp.StatusCode.ToString());

            }
        }
        //Output JSON parsing error
        catch (Exception e)
        {
            FailComponent(e.ToString());
        }
        return jsonResponse;
    }

Here are two lanes I am suspicious about:

WCProduct[] wcProductOutput = GetRestServiceResult1(wcApiCompleteUrl);
           
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?
BurzhuinAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Duy PhamFreelance IT ConsultantCommented:
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?
BurzhuinAuthor Commented:
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.
BurzhuinAuthor Commented:
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&consumer_secret=KEY

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.
Active Protection takes the fight to cryptojacking

While there were several headline-grabbing ransomware attacks during in 2017, another big threat started appearing at the same time that didn’t get the same coverage – illicit cryptomining.

BurzhuinAuthor Commented:
I received no errors or warnings when I compiled and run the package.
Duy PhamFreelance IT ConsultantCommented:
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:

WCProducts jsonRoot = DeserializeJSon<WCProducts>(jsonString);
jsonResponse = jsonRoot.Product;

Open in new window


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?
Duy PhamFreelance IT ConsultantCommented:
I think the cause is in your response data.

Response should be:

{ "product": [{ "title": ..... attributes: [{...}] }] }

Open in new window


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);
        }

Open in new window

BurzhuinAuthor Commented:
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.
BurzhuinAuthor Commented:
I noticed that result of execution the following line:

WCProduct[] wcProductOutput = GetRestServiceResult1(wcApiCompleteUrl);

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(string wUrl)
    {

        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);

        if (Variables.UseStandardProxy)
        {
            httpWReq.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
            httpWReq.PreAuthenticate = true;
        }
        HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
        WCProduct[] jsonResponse = null;

        try
        {
            //Test the connection
            if (httpWResp.StatusCode == HttpStatusCode.OK)
            {

                //Stream responseStream = httpWResp.GetResponseStream();
                string jsonString = null;

                //Set jsonString using a stream reader
                using (StreamReader reader = new StreamReader(httpWResp.GetResponseStream(), System.Text.Encoding.UTF8))
                {
                    jsonString = reader.ReadToEnd();// Replace("\\", "");
                    reader.Close();
                }
                WCProducts jsonRoot = DeserializeJSon<WCProducts>(jsonString);
                jsonResponse = jsonRoot.Product;
            }
            //Output connection error message
            else
            {
                FailComponent(httpWResp.StatusCode.ToString());

            }
        }
        //Output JSON parsing error
        catch (Exception e)
        {
            FailComponent(e.ToString());
        }
        return jsonResponse;
    }
Duy PhamFreelance IT ConsultantCommented:
Your problem is in the response data, not the client-code to deserialize the data.

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"]
         }...]
    }
}

Open in new window


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
}

Open in new window


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; }
 }

Open in new window


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;
}

Open in new window


But not that, option #2 only returns a single WCProduct object. It might not be your intention, so you should consider option #1.
BurzhuinAuthor Commented:
WebService in my case returns:

      "{\"product\":{\"title\":\"Individual Ticket (Aspire)\",\"id\":29861,\"created_at\":\"2015-01-05T21:06:42Z\",\"updated_at\":\"2015-03-30T14:24:18Z\",\"type\":\"simple\",\"status\":\"publish\",\"downloadable\":false,\"virtual\":true,\"permalink\":\"https:\\/\\/apibuild.giving.massgeneral.org\\/product\\/corporate-individual-ticket-aspire\\/\",\"sku\":\"2015-aspire-single-corporate-ticket\",\"price\":\"500.00\",\"regular_price\":\"500.00\",\"sale_price\":null,\"price_html\":\"<span class=\\\"woocommerce-price-before\\\"> <\\/span><span class=\\\"amount\\\">&#36;500.00<\\/span><span class=\\\"woocommerce-price-after\\\"> <\\/span>\",\"taxable\":false,\"tax_status\":\"taxable\",\"tax_class\":\"\",\"managing_stock\":false,\"stock_quantity\":0,\"in_stock\":true,\"backorders_allowed\":false,\"backordered\":false,\"sold_individually\":false,\"purchaseable\":true,\"featured\":false,\"visible\":true,\"catalog_visibility\":\"catalog\",\"on_sale\":false,\"weight\":null,\"dimensions\":{\"length\":\"\",\"width\":\"\",\"height\":\"\",\"unit\":\"in\"},\"shipping_required\":false,\"shipping_taxable\":true,\"shipping_class\":\"\",\"shipping_class_id\":null,\"description\":\"<ul>\\n<li>One ticket to\\u00a0Aspire 2015<\\/li>\\n<li>Listing in the annual Mass General Donor Report<\\/li>\\n<\\/ul>\\n\",\"short_description\":\"<ul>\\n<li>One ticket to\\u00a0Aspire 2015<\\/li>\\n<li>Listing in the annual Mass General Donor Report<\\/li>\\n<\\/ul>\\n\",\"reviews_allowed\":false,\"average_rating\":\"0.00\",\"rating_count\":0,\"related_ids\":[32051,32132,32134,32135,32136],\"upsell_ids\":[],\"cross_sell_ids\":[],\"parent_id\":0,\"categories\":[\"Aspire\"],\"tags\":[],\"images\":[{\"id\":0,\"created_at\":\"2015-03-30T18:50:49Z\",\"updated_at\":\"2015-03-30T18:50:49Z\",\"src\":\"\\/plugins\\/woocommerce\\/assets\\/images\\/placeholder.png\",\"title\":\"Placeholder\",\"alt\":\"Placeholder\",\"position\":0}],\"featured_src\":false,\"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\":\"3\",\"visible\":false,\"variation\":false,\"options\":[\"027604\"]},{\"name\":\"Re-benefit-value\",\"position\":\"4\",\"visible\":false,\"variation\":false,\"options\":[\"200\"]}],\"downloads\":[],\"download_limit\":0,\"download_expiry\":0,\"download_type\":\"\",\"purchase_note\":\"<p>$300.00 of the purchase of each ticket is tax-deductible to the full extent of the law<\\/p>\\n\",\"total_sales\":67,\"variations\":[],\"parent\":[]}}"      string

If this is not an array, I do not know what it is.
BurzhuinAuthor Commented:
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.
Duy PhamFreelance IT ConsultantCommented:
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/.
Duy PhamFreelance IT ConsultantCommented:
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:
Change definition of WCProducts class:

[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 }; ... }
BurzhuinAuthor Commented:
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 };
Duy PhamFreelance IT ConsultantCommented:
It seems that you declared jsonResponse as WCProduct, it should be WCProduct[] as your original code:

WCProduct[]  jsonResponse = null;

Open in new window

BurzhuinAuthor Commented:
Is there any other way?
BurzhuinAuthor Commented:
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;
BurzhuinAuthor Commented:
Is there any way to jump to attributes?
Duy PhamFreelance IT ConsultantCommented:
To return WCProduct[], your function should be:

function WCProduct[] GetRestServiceResult1(...)
{
...
WCProduct[] jsonResponse = null;
...
WCProducts jsonRoot = DeserializeJSon<WCProducts>(jsonString);
jsonResponse = new WCProduct[] { jsonRoot.Product };
...
return jsonResponse;
}

Open in new window


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;
}

Open in new window

BurzhuinAuthor Commented:
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.Serialization.SerializationException: There was an error deserializing the object of type WCProducts. Encountered unexpected character ':'. ---> System.Xml.XmlException: Encountered unexpected character ':'.
   at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
   at System.Runtime.Serialization.Json.XmlJsonReader.Read()
   at System.Xml.XmlBaseReader.Skip()
   at System.Runtime.Serialization.XmlReaderDelegator.Skip()
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.SkipUnknownElement(XmlReaderDelegator xmlReader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, Int32 memberIndex)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, Int32 memberIndex, ExtensionDataObject extensionData)
   at ReadWCProductFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
   at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadWCProductsFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
   at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName)
   at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   --- End of inner exception stack trace ---
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(Stream stream)
   at ScriptMain.DeserializeJSon[T](String jsonString) in c:\Users\rk688\AppData\Local\Temp\Vsta\b535f4d68b0f423cb79f6e346702f8a0\main.cs:line 562
   at ScriptMain.GetRestServiceResult1(String wUrl) in c:\Users\rk688\AppData\Local\Temp\Vsta\b535f4d68b0f423cb79f6e346702f8a0\main.cs:line 530


2. [Error Getting Data From Webservice!] Error: System.NullReferenceException: Object reference not set to an instance of an object.
   at ScriptMain.CreateAttribute(String ProdID, Int32 counter) in c:\Users\rk688\AppData\Local\Temp\Vsta\b535f4d68b0f423cb79f6e346702f8a0\main.cs:line 384

Should I remove columns ":" from jsonString?
BurzhuinAuthor Commented:
I run second time and I got different error:

[Error Getting Data From Webservice!] Error: System.Runtime.Serialization.SerializationException: 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.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
   at System.Xml.XmlExceptionHelper.ThrowEndElementExpected(XmlDictionaryReader reader, String localName, String ns)
   at System.Xml.XmlBaseReader.ReadEndElement()
   at System.Xml.XmlBaseReader.ReadElementContentAsString()
   at System.Runtime.Serialization.XmlReaderDelegator.ReadElementContentAsString()
   at ReadWCAttributeFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
   at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadArrayOfWCAttributeFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString , CollectionDataContract )
   at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadWCProductFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
   at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 id, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle, String name, String ns)
   at ReadWCProductsFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString , XmlDictionaryString[] )
   at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.JsonDataContract.ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context)
   at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName)
   at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   --- End of inner exception stack trace ---
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader)
   at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(Stream stream)
   at ScriptMain.DeserializeJSon[T](String jsonString) in c:\Users\rk688\AppData\Local\Temp\Vsta\56a31aa1c0b2490aba5b143011be11a5\main.cs:line 562
   at ScriptMain.GetRestServiceResult1(String wUrl) in c:\Users\rk688\AppData\Local\Temp\Vsta\56a31aa1c0b2490aba5b143011be11a5\main.cs:line 530
Duy PhamFreelance IT ConsultantCommented:
There was an error deserializing the object of type WCProducts. Encountered unexpected character ':'. ---> System.Xml.XmlException: Encountered unexpected character ':'.
This means your json string response is not well-formatted. Please post the json string response that causes the error here, otherwise we can't help anything at all. Or you can post and validate your json string response online at: http://json.parser.online.fr/.

I've also attached a sample code that works just fine deserializing your json string response posted in comment:  40696828.
Program.cs

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BurzhuinAuthor Commented:
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!!!!!
BurzhuinAuthor Commented:
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.
Duy PhamFreelance IT ConsultantCommented:
You are welcome, and great to hear that it helps :).
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.