2016-06-27 4 views
0

Я получаю данные из одного API и POST в другой API, но некоторые записи заканчиваются ошибкой. Я выяснил, что в полях исходного API есть незаконные символы.Незаконные символы/Escape-необходимые символы для JSON

К сожалению, есть ограничения на моем назначения API из-за которой я не могу использовать URLEncode.encode, убегая и т.д. или любой другой content-type но application/json, а также по другим причинам, мой единственный вариант, чтобы вручную найти и удалить эти символы с заранее определенными символами замены, как пространство/дефис. Мой клиент также согласился на этот подход. Теперь я не знаю всех этих персонажей.

по мне следующие символы возникают проблемы:

‘ 
” 
\ 
{ 
} 
[ 
] 

является приведенный выше список полный и правильный


P.S. Образец данных 1

{ 
"name": "JSW-13867", 
"description": "Hi, 

    It would be extremely useful 
if it was possible to assign dates in the scrum board columns. 

#We already configure the sprint end date, 
so that could be displayed in the last column.\\\\ 
So, 
in our 
case, 
currently the last column is named "Done". 
What we 'd like to see is "Done (by 08/Jul/16)"\\\\ 
Although this information is 1 click away, 
so it wouldn 't be that big of an improvement (though easy to implement). But it makes sense if #2 below is implemented too.\\\\# 
What would be important in our 
case is the one - to - last column, 
which is "Test Done".\\\\ 
That would become "Test Done (by 01/Jul/16)".\\\\ 
What would be probably the correct/concise way, 
is a configuration on a board level, 
of an X amount of days before the sprint end date, 
for any column;which, 
ifset, 
will be displayed as per my examples(or similar). 

The last sentence of #2 is my recommendation/feature request... 

Thanks for a great product :) \\ 
\\ 
---- 
\\ 
original post: https://answers.atlassian.com/questions/39228431/answers/39228618","fields": {"field": [{"dataType": "ENUM_TYPE","id": "1716","name": "KFH-Issue-Issue Details:Issue Rating","hasChanged": true,"enumValue": {"name": "Very Low"}},{"dataType": "ENUM_TYPE","id": "530","name": "OPSS-Iss:Status","hasChanged": false,"enumValue": {"name": "Open"}},{"dataType": "ENUM_TYPE","id": "1717","name": "KFH-Issue-Issue Details:Issue Source","hasChanged": false,"enumValue": {"id": "4333","name": "IAD","index": 2,"hidden": false}}]}, "typeDefinitionId": "24", "primaryParentId": "26982"} 

p.s. Данные Пример 2

{ 
"name": "JSW-13840", 
"description": " h3. Summary If we set the *Incoming Authentication* on Fisheye side towards connection from JIRA and have the Executed As field specified by a user, the trigger creation will be mentioned that there is a problem with the configuration and mention that Fisheye status is Not Working  h3. Steps to Reproduce # Integrate JIRA with Fisheye. # Make sure that Fisheye is connected to a repo and at least One commit mentioning a JIRA ticket. # Edit OAuth Incoming Authentication on Fisheye side for connection with JIRA and set the Execute As field. # Update the configuration. # Navigate to JIRA and add a trigger to a specific workflow transition h3. Expected Result - The Diagnostics will state that the connection is Working  h3. Actual Result - The Diagnostics state that Fisheye connection is Not Working  h3. Notes - Using JIRA 7.1.7 and FerCru 4.0.4 - Tested this with 2LOi and it mention that there is no problem with the configuration. But, if we added a user on that particular field, it will back to Not Working after refreshing the page. - Samse as 2LOi, 2LO without any additional settings also did not have any issue. - Result of the diagnostic with Execute as {code}{ appLinkDiagnosticResults [{ name Julians-MacBook-Pro , type FishEye/Crucible , icon http //localhost 8717/jira_717/s/en_US-6hktwl/71011/b6b48b2829824b869586ac216d119363/5.0.7/_/download/resources/com.atlassian.applinks.applinks-plugin applinks-images/images/types/16fecru.png , supportedVersion true, accessible true, inboundStatus null, outboundStatus NOT_AUTHENTICATED , local2LOConfigured OK , remote2LOConfigured NOT_TESTED , working false}], dvcsDiagnosticResult { dvcsAccountDiagnosticResults []}, devToolsDocoUrl https //docs.atlassian.com/jira/jcore-docs-071/Integrating+JIRA+with+Code+Development+Tools {code} - Result of the diagnostic for aynthing without Execute as {code} { appLinkDiagnosticResults [{ name Julians-MacBook-Pro , type FishEye/Crucible , icon http //localhost 8717/jira_717/s/en_US-6hktwl/71011/b6b48b2829824b869586ac216d119363/5.0.7/_/download/resources/com.atlassian.applinks.applinks-plugin applinks-images/images/types/16fecru.png , supportedVersion true, accessible true, inboundStatus WORKING , outboundStatus WORKING , local2LOConfigured OK , remote2LOConfigured OK , working true}], dvcsDiagnosticResult { dvcsAccountDiagnosticResults []}, devToolsDocoUrl https //docs.atlassian.com/jira/jcore-docs-071/Integrating+JIRA+with+Code+Development+Tools } {code}", 
"fields": { 
    "field": [{ 
     "dataType": "ENUM_TYPE", 
     "id": "1716", 
     "name": "KFH-Issue-Issue Details:Issue Rating", 
     "hasChanged": true, 
     "enumValue": { 
      "name": "Low" 
     } 
    }, { 
     "dataType": "ENUM_TYPE", 
     "id": "530", 
     "name": "OPSS-Iss:Status", 
     "hasChanged": false, 
     "enumValue": { 
      "name": "Open" 
     } 
    }, { 
     "dataType": "ENUM_TYPE", 
     "id": "1717", 
     "name": "KFH-Issue-Issue Details:Issue Source", 
     "hasChanged": false, 
     "enumValue": { 
      "id": "4333", 
      "name": "IAD", 
      "index": 2, 
      "hidden": false 
     } 
    }] 
}, 
"typeDefinitionId": "24", 
"primaryParentId": "26982" 
} 
+1

Почему бы вам не избежать их должным образом, как и все остальные? json escape! = url-encode -> http://stackoverflow.com/questions/3020094/how-should-i-escape-strings-in-json – zapl

+0

Я пробовал это, мой целевой API поддерживает только контент 'application/json' , Таким образом, строки кодирования заканчиваются, ну, вы знаете, как выглядит закодированная строка. Побег не практичен, я должен разбирать каждый ключ каждого объекта и убегать. Невозможно практиковать. – Moon

+1

способ избежать определяется 'application/json', когда API фактически поддерживает этот формат, он также поддерживает экранирование. edit: это ваше построение кода, которое является образцом данных или происходит из другого места, и вы не можете его изменить? – zapl

ответ

0

Я предлагаю вам использовать библиотеку Java JSON, чтобы правильно JSON данных кодируют для назначения API. Если бы вы предоставили пример данных, мы могли бы помочь вам больше.

UPDATE: Вот код, который работает с вашими данными

public static void main(String[] args) { 
    String desc = "\"description\": \""; 
    String fields = "\",\"fields\""; 
    int indexStart = njson.indexOf(desc) + desc.length() ; 
    int indexEnd = njson.indexOf(fields); 

    String ex = njson.substring(indexStart, indexEnd); 

    String str = JSONObject.quote(ex); 

    String begin = njson.substring(0, indexStart - 1); 
    String end = njson.substring(indexEnd + 1); 

    String validJSon = begin + str + end; 

    JSONObject obj = new JSONObject(validJSon); 
} 

njson является строка из вашего примера

+0

пример отправлен выше – Moon

+0

@Moon да, это недействительный JSON. В поле «description» у вас есть двойные кавычки. Отсюда вы можете взять подстроку из «описания» в «поля» и просто JSON кодирует эту подстроку, после чего у вас будет действительный объект JSON. – madatx

+0

он сработал. Также вышеупомянутый метод заменяет и экранирует специальные символы. Есть только 1 из моих 50 записей, которые проходят оба этикета. См. Пример данных 2 – Moon