简体   繁体   English

解析相同数据的JSON错误-Newtonsoft.Json

[英]JSON Error Parsing Identical Data - Newtonsoft.Json

We have a webservice that is used to work with our third-party services. 我们有一个用于与第三方服务一起使用的Web服务。 One of those is SmartyStreets, which is used to validate US Addresses. 其中之一是SmartyStreets,用于验证美国地址。 Here is my issue: randomly, there is a JSON parsing error. 这是我的问题:随机地,有一个JSON解析错误。 Resubmitting the address seems to work fine. 重新提交地址似乎正常。 I can't find no specific thing that indicates the issue. 我找不到指示问题的具体内容。 Below is the URL: 以下是网址:

https://us-street.api.smartystreets.com/street-address?auth-id=xxxxx&auth-token=xxxxx&street=4952+W+STRONG+ST++CHICAGO+IL+60630-2420&candidates=10

Nothing special, right? 没什么特别的吧?

Here is the response: 这是响应:

{"input_index":0,"candidate_index":0,"delivery_line_1":"4952 W Strong St","last_line":"Chicago IL 60630-2420","delivery_point_barcode":"606302420520","components":{"primary_number":"4952","street_predirection":"W","street_name":"Strong","street_suffix":"St","city_name":"Chicago","state_abbreviation":"IL","zipcode":"60630","plus4_code":"2420","delivery_point":"52","delivery_point_check_digit":"0"},"metadata":{"record_type":"S","zip_type":"Standard","county_fips":"17031","county_name":"Cook","carrier_route":"C021","congressional_district":"05","rdi":"Residential","elot_sequence":"0079","elot_sort":"A","latitude":41.97079,"longitude":-87.75191,"precision":"Zip9","time_zone":"Central","utc_offset":-6,"dst":true},"analysis":{"dpv_match_code":"Y","dpv_footnotes":"AABB","dpv_cmra":"N","dpv_vacant":"N","active":"Y"}}

That response had an error (and yes, I know, no [], I purposely take them out). 该响应有一个错误(是的,我知道,没有[],我故意将其取出)。 Below is an identical response made a few seconds later: 以下是几秒钟后做出的相同答复:

{"input_index":0,"candidate_index":0,"delivery_line_1":"4952 W Strong St","last_line":"Chicago IL 60630-2420","delivery_point_barcode":"606302420520","components":{"primary_number":"4952","street_predirection":"W","street_name":"Strong","street_suffix":"St","city_name":"Chicago","state_abbreviation":"IL","zipcode":"60630","plus4_code":"2420","delivery_point":"52","delivery_point_check_digit":"0"},"metadata":{"record_type":"S","zip_type":"Standard","county_fips":"17031","county_name":"Cook","carrier_route":"C021","congressional_district":"05","rdi":"Residential","elot_sequence":"0079","elot_sort":"A","latitude":41.97079,"longitude":-87.75191,"precision":"Zip9","time_zone":"Central","utc_offset":-6,"dst":true},"analysis":{"dpv_match_code":"Y","dpv_footnotes":"AABB","dpv_cmra":"N","dpv_vacant":"N","active":"Y"}}

The response above did not have an error and worked fine. 上面的响应没有错误,并且工作正常。 The error from the first one is below: 来自第一个的错误如下:

-+Exception:
Newtonsoft.Json.JsonReaderException
-+Message:
Additional text encountered after finished reading JSON content: }. Path '', line 1, position 820.
-+Stack Trace:
at Newtonsoft.Json.JsonTextReader.Read()
at Newtonsoft.Json.Linq.JObject.Parse(String json, JsonLoadSettings settings)
at Newtonsoft.Json.Linq.JObject.Parse(String json)
at POS.Backend.Services.Providers.SmartyStreetsProvider.ValidateAddress_2622(String addressToValidate, EntityType entityType, Nullable`1 entityID, String entityName, Int32 storeID, Int32 tellerID) in C:\Users\Wayen\Documents\Projects\GIT\dPoint\Backend\Providers\SmartyStreetsProvider.cs:line 128

Can anyone see a difference? 谁能看到有所不同? I can't. 我不能 I have absolutely no idea why the first has an error and the second does not. 我完全不知道为什么第一个有错误而第二个没有。

Here is the code where the error occurs: 这是发生错误的代码:

List<SmartyStreetsAPIResponseAddressResult> foundAddresses = new List<SmartyStreetsAPIResponseAddressResult>();

            jsonResponse = jsonResponse.Replace("[", "").Replace("]", "");  //remove the extra [ ] at the start & end
            string[] candidates = jsonResponse.Split(new string[] { "},{" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string candidate in candidates)
            {
                //the split can remove parts of the JSON return value. Restore these parts
                string correctedCandidateJSONValue = candidate;
                if (correctedCandidateJSONValue.Substring(correctedCandidateJSONValue.Length - 2, 2) != "}\n" )
                    correctedCandidateJSONValue += "}";

                if (correctedCandidateJSONValue.Substring(0, 1) != "{")
                    correctedCandidateJSONValue = correctedCandidateJSONValue.Insert(0, "{");

                JObject addressData = JObject.Parse(correctedCandidateJSONValue);

The error occurs on the JObject.Parse(correctedCandidateJSONValue) line. 该错误发生在JObject.Parse(correctedCandidateJSONValue)行上。 Randomly. 随便 By the way, this just started a week ago; 顺便说一下,这是一周前开始的; there have been no code changes in nearly a year. 近一年没有代码更改。

Sometimes the JSON does come back with an additional tag, such as "footnotes" 有时JSON确实会附带一个附加标签,例如“脚注”

 {"input_index":0,"candidate_index":0,"delivery_line_1":"900 S Clark St","last_line":"Chicago IL 60605-3679","delivery_point_barcode":"606053679990","components":{"primary_number":"900","street_predirection":"S","street_name":"Clark","street_suffix":"St","city_name":"Chicago","state_abbreviation":"IL","zipcode":"60605","plus4_code":"3679","delivery_point":"99","delivery_point_check_digit":"0"},"metadata":{"record_type":"H","zip_type":"Standard","county_fips":"17031","county_name":"Cook","carrier_route":"C025","congressional_district":"07","building_default_indicator":"Y","rdi":"Residential","elot_sequence":"0454","elot_sort":"A","latitude":41.87051,"longitude":-87.63065,"precision":"Zip9","time_zone":"Central","utc_offset":-6,"dst":true},"analysis":{"dpv_match_code":"D","dpv_footnotes":"AAN1","dpv_cmra":"N","dpv_vacant":"N","active":"Y","footnotes":"H#"}}

It's been fixed, thanks to dbc. 由于dbc,它已修复。 My updated code is below: 我的更新代码如下:

            JsonSerializerSettings serializeSettings = new JsonSerializerSettings() { CheckAdditionalContent = false };
            object deserializedJson = JsonConvert.DeserializeObject(jsonResponse, serializeSettings);

            foreach (JObject candidate in (JArray)(deserializedJson))
            {
                //get only the address parts we need, which is the two lines (free-form) + the number, direction, name, suffix, city, state abbr, and zip code, along with PO BOX info if available
                JToken lineOne = candidate.SelectToken("delivery_line_1");
                JToken lineTwo = candidate.SelectToken("last_line");

                JToken houseNumber = candidate.SelectToken("components.primary_number");
                JToken directionToken = candidate.SelectToken("components.street_predirection");
                JToken streetName = candidate.SelectToken("components.street_name");
                JToken streetSuffix = candidate.SelectToken("components.street_suffix");
                JToken city = candidate.SelectToken("components.city_name");
                JToken state = candidate.SelectToken("components.state_abbreviation");
                JToken zipCode = candidate.SelectToken("components.zipcode");

                bool isPOBox = false;

                if (lineOne.ToString().ToLower().Contains("po box"))
                {
                    isPOBox = true;
                }

                JToken county = candidate.SelectToken("metadata.county_name");
                foundAddresses.Add(new SmartyStreetsAPIResponseAddressResult((lineOne != null ? lineOne.ToString() : string.Empty),
                    (lineTwo != null ? lineTwo.ToString() : string.Empty),
                    (houseNumber != null ? houseNumber.ToString() : string.Empty),
                    (directionToken != null ? directionToken.ToString() : string.Empty),
                    (streetName != null ? streetName.ToString() : string.Empty),
                    (streetSuffix != null ? streetSuffix.ToString() : string.Empty),
                    (city != null ? city.ToString() : string.Empty),
                    (state != null ? state.ToString() : string.Empty),
                    (zipCode != null ? zipCode.ToString() : string.Empty),
                    (county != null ? county.ToString() : string.Empty),
                    isPOBox));
            }

Like I said in my comment, I'm new to JSON. 就像我在评论中说的那样,我是JSON的新手。 Instead of reading up on how it works, I took a look at the string returned from the service and tried to parse it myself. 我没有阅读它的工作原理,而是查看了从服务返回的字符串,并尝试自己解析它。 I split it by brackets and iterated through that rather than deserializing it with the right settings. 我用方括号将其分开,并对其进行遍历,而不是使用正确的设置对其进行反序列化。 The updated code works great now. 更新的代码现在可以很好地工作了。 Thanks dbc! 谢谢dbc!

Per dbc, answer is below: 根据dbc,答案如下:

            JsonSerializerSettings serializeSettings = new JsonSerializerSettings() { CheckAdditionalContent = false };
            object deserializedJson = JsonConvert.DeserializeObject(jsonResponse, serializeSettings);

            foreach (JObject candidate in (JArray)(deserializedJson))
            {
                //get only the address parts we need, which is the two lines (free-form) + the number, direction, name, suffix, city, state abbr, and zip code, along with PO BOX info if available
                JToken lineOne = candidate.SelectToken("delivery_line_1");
                JToken lineTwo = candidate.SelectToken("last_line");

                JToken houseNumber = candidate.SelectToken("components.primary_number");
                JToken directionToken = candidate.SelectToken("components.street_predirection");
                JToken streetName = candidate.SelectToken("components.street_name");
                JToken streetSuffix = candidate.SelectToken("components.street_suffix");
                JToken city = candidate.SelectToken("components.city_name");
                JToken state = candidate.SelectToken("components.state_abbreviation");
                JToken zipCode = candidate.SelectToken("components.zipcode");

                bool isPOBox = false;

                if (lineOne.ToString().ToLower().Contains("po box"))
                {
                    isPOBox = true;
                }

                JToken county = candidate.SelectToken("metadata.county_name");
                foundAddresses.Add(new SmartyStreetsAPIResponseAddressResult((lineOne != null ? lineOne.ToString() : string.Empty),
                    (lineTwo != null ? lineTwo.ToString() : string.Empty),
                    (houseNumber != null ? houseNumber.ToString() : string.Empty),
                    (directionToken != null ? directionToken.ToString() : string.Empty),
                    (streetName != null ? streetName.ToString() : string.Empty),
                    (streetSuffix != null ? streetSuffix.ToString() : string.Empty),
                    (city != null ? city.ToString() : string.Empty),
                    (state != null ? state.ToString() : string.Empty),
                    (zipCode != null ? zipCode.ToString() : string.Empty),
                    (county != null ? county.ToString() : string.Empty),
                    isPOBox));
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM