web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

JSON Deserialization fails

(0) ShareShare
ReportReport
Posted on by 55

Hello Community,

I'm struggling with deserializing a JSON response that I'm getting from my own D365FO oData endpoint :

System.ArgumentException :

HResult=0x80070057
Message=Invalid JSON primitive: { "value":[ { "dataAreaId":"usa1","CustomerGroupId":"10","ClearingPeriodPaymentTermName":"","CustomerAccountNumberSequence":"","DefaultDimensionDisplayValue":"","Description":"Retail","IsSalesTaxIncludedInPrice":"No","WriteOffReason":"","PaymentTermId":"N30","TaxGroupId":"","IsPublicSector_IT":"No" },{ "dataAreaId":"usa1","CustomerGroupId":"20","ClearingPeriodPaymentTermName":"","CustomerAccountNumberSequence":"","DefaultDimensionDisplayValue":"","Description":"Wholesale","IsSalesTaxIncludedInPrice":"No","WriteOffReason":"","PaymentTermId":"","TaxGroupId":"","IsPublicSector_IT":"No" } ]}.
Source=System.Web.Extensions
StackTrace:
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
....

If I convert that JSON on a website such as https://codebeautify.org/jsonviewer it processes just fine. I appreciate your help.

//URL to get data
webRequest = RetailWebRequest::newUrl(URL);

//Send token through JSON GET call
webRequest.parmHeader(@'Authorization: Bearer '+token);
webRequest.parmContentType("application/json;odata.metadata=none");
webRequest.parmMethod("GET");

response = webApi.getResponse(webRequest);

if(response.parmHttpStatus() != 200)
throw error("No data is returned");

rawResponse = substr(response.parmData(),2,(strlen(response.parmData())-2));

// responseData = RetailCommonWebAPI::getMapFromJsonString(rawResponse);

System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();

ser.MaxJsonLength = maxInt();

rawResponse = strRem(rawResponse,/*"\"" +*/ "\t" + "\r" + "\n" + "\r\n" + "\\" +"\b" + "\f");

rawResponse = "\"Values\": {" + rawResponse; // I also tried without wrapping the JSON into another "Values" segment

rawResponse += "}";

CLRObject x = ser.DeserializeObject(rawResponse); <-- Boooom

rawReponse :"\"Values\": {  \"value\":[    {      \"dataAreaId\":\"usa1\",\"CustomerGroupId\":\"10\",\"ClearingPeriodPaymentTermName\":\"\",\"CustomerAccountNumberSequence\":\"\",\"DefaultDimensionDisplayValue\":\"\",\"Description\":\"Retail\",\"IsSalesTaxIncludedInPrice\":\"No\",\"WriteOffReason\":\"\",\"PaymentTermId\":\"N30\",\"TaxGroupId\":\"\",\"IsPublicSector_IT\":\"No\"    },{      \"dataAreaId\":\"usa1\",\"CustomerGroupId\":\"20\",\"ClearingPeriodPaymentTermName\":\"\",\"CustomerAccountNumberSequence\":\"\",\"DefaultDimensionDisplayValue\":\"\",\"Description\":\"Wholesale\",\"IsSalesTaxIncludedInPrice\":\"No\",\"WriteOffReason\":\"\",\"PaymentTermId\":\"\",\"TaxGroupId\":\"\",\"IsPublicSector_IT\":\"No\"    },{      \"dataAreaId\":\"usa1\",\"CustomerGroupId\":\"30\",\"ClearingPeriodPaymentTermName\":\"\",\"CustomerAccountNumberSequence\":\"\",\"DefaultDimensionDisplayValue\":\"\",\"Description\":\"Distributor\",\"IsSalesTaxIncludedInPrice\":\"No\",\"WriteOffReason\":\"\",\"PaymentTermId\":\"\",\"TaxGroupId\":\"\",\"IsPublicSector_IT\":\"No\"    },{      \"dataAreaId\":\"usa1\",\"CustomerGroupId\":\"40\",\"ClearingPeriodPaymentTermName\":\"\",\"CustomerAccountNumberSequence\":\"\",\"DefaultDimensionDisplayValue\":\"\",\"Description\":\"Broker\",\"IsSalesTaxIncludedInPrice\":\"No\",\"WriteOffReason\":\"\",\"PaymentTermId\":\"\",\"TaxGroupId\":\"\",\"IsPublicSector_IT\":\"No\"    },{      \"dataAreaId\":\"usa1\",\"CustomerGroupId\":\"90\",\"ClearingPeriodPaymentTermName\":\"\",\"CustomerAccountNumberSequence\":\"\",\"DefaultDimensionDisplayValue\":\"\",\"Description\":\"test\",\"IsSalesTaxIncludedInPrice\":\"No\",\"WriteOffReason\":\"\",\"PaymentTermId\":\"\",\"TaxGroupId\":\"\",\"IsPublicSector_IT\":\"No\"    },{      \"dataAreaId\":\"usa1\",\"CustomerGroupId\":\"99\",\"ClearingPeriodPaymentTermName\":\"\",\"CustomerAccountNumberSequence\":\"\",\"DefaultDimensionDisplayValue\":\"\",\"Description\":\"Other\",\"IsSalesTaxIncludedInPrice\":\"No\",\"WriteOffReason\":\"\",\"PaymentTermId\":\"\",\"TaxGroupId\":\"\",\"IsPublicSector_IT\":\"No\"    },{      \"dataAreaId\":\"usa1\",\"CustomerGroupId\":\"Default\",\"ClearingPeriodPaymentTermName\":\"\",\"CustomerAccountNumberSequence\":\"\",\"DefaultDimensionDisplayValue\":\"\",\"Description\":\"\",\"IsSalesTaxIncludedInPrice\":\"No\",\"WriteOffReason\":\"\",\"PaymentTermId\":\"\",\"TaxGroupId\":\"\",\"IsPublicSector_IT\":\"No\"    }  ]}"

I have the same question (0)
  • huijij Profile Picture
    19,811 on at

    Hi,

    Please refer the Sumit's answer about deserializing the Json response:

    community.dynamics.com/.../deserialize-the-json-response

  • Suggested answer
    Martin Dráb Profile Picture
    237,805 Most Valuable Professional on at

    Unfortunately I'm not much familiar with JavaScriptSerializer, but according its documentation, you must implement and register a custom converter if you're deserializing a type that isn't natively supported by JavaScriptSerializer. I don't see such a thing in your code.

    I think you should rather choose either one of the options available in F&O, or Newtonsoft.Json. Check out the thread references by Judy to see a bit more details.

    By the way, please always use Insert > Insert Code to paste source code. You can even enable syntax highlighting for C# and JSON there.

  • Darrell Crews Profile Picture
    55 on at

    Judy, thanks, but 

    rootMap = RetailCommonWebAPI::getMapFromJSONString(respsonse);

    calls them same serializer I'm using resulting in the same error. The only difference is that I made the maxSize bigger.

    public static Map getMapFromJsonString(str _jsonString)

       {

           Map result;

           System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();

           CLRObject dict = ser.DeserializeObject(_jsonString);

           result = RetailCommonWebAPI::getMap(dict);

           return result;

       }

  • Suggested answer
    ergun sahin Profile Picture
    8,826 Moderator on at

    Is there any particular reason to use JavaScriptSerializer? Otherwise, don't waste too much time and change methods. I usually use NewtonSoft.
    I shared the classes you will use for deserialize below. (https://json2csharp.com)

    // Root myDeserializedClass = JsonConvert.DeserializeObject(myJsonResponse); 
        public class Value
        {
            public string dataAreaId { get; set; }
            public string CustomerGroupId { get; set; }
            public string ClearingPeriodPaymentTermName { get; set; }
            public string CustomerAccountNumberSequence { get; set; }
            public string DefaultDimensionDisplayValue { get; set; }
            public string Description { get; set; }
            public string IsSalesTaxIncludedInPrice { get; set; }
            public string WriteOffReason { get; set; }
            public string PaymentTermId { get; set; }
            public string TaxGroupId { get; set; }
            public string IsPublicSector_IT { get; set; }
        }
    
        public class Values
        {
            public List value { get; set; }
        }
    
        public class Root
        {
            public Values Values { get; set; }
        }

  • Suggested answer
    Frank Bruemmer Profile Picture
    354 on at

    Please try this :

    You will need two contract classes : one for the object, one for the (each specific) entity.

           JSONObjectContract jSONObjectContract = FormJsonSerializer::deserializeObject(classNum(jSONObjectContract),rawResponse);

           List listData = new List(Types::Class);

           listData = jSONObjectContract.parmData();

           ListEnumerator listEnumerator = listData.getEnumerator();

           if(listEnumerator == null)

           throw error("Can't get list enumerator");

           while (listEnumerator.moveNext())

           {

               JSONDataContract jsonDataContract = listEnumerator.current();

               info(JSONDataContract.CustomerGroupId() + ' ' + JSONDataContract.Description());

           }

    [..]

    [DataContract]

    class JSONObjectContract

    {

       str status;

       List data;

       [DataMember("status")]

       public str parmStatus(String50 _status = Status)

       {

           status = _status;

           return status;

       }

       [   DataMemberAttribute('value'),

           DataCollectionAttribute(Types::Class,classStr(JSONDataContract))

       ]

       public List parmData(List _data = data)

       {

           data = _data;

           return data;

       }

    }

    [..]

    [DataContract]

    class JSONDataContract

    {

       str CustomerGroupId;

       str DataAreaId;

       str Description;

       [DataMember("CustomerGroupId")]

       public str CustomerGroupId(String50 _customerGroupId = CustomerGroupId)

       {

           CustomerGroupId = _customerGroupId;

           return CustomerGroupId;

       }

       [DataMember("DataAreaId")]

       public str DataAreaId(String50 _dataAreaId = DataAreaId)

       {

           DataAreaId = _dataAreaId;

           return DataAreaId;

       }

       [DataMember("Description")]

       public str Description(String50 _description = Description)

       {

           Description = _description;

           return Description;

       }

    }

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 664 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 522 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 303 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans