2015-10-15 2 views
1

Я строю Java-API 2-го интерфейса Java (сканер). Сканер извлекает текст из статей и возвращает его в json. API позже будет использоваться другими разработчиками.Хороший способ «сохранить» символ новой строки в JSON?

Так что мой вопрос: как я могу «сохранить» символы новой строки в строке в моем json-файле?

Пример другой службы решения этой проблемы (выход JSON):

"text": "When Etsy bought Grand St. last April, . But that’s about to change. At the end of this month, Grand St. will stop processing orders and on October 1, listings on the site will become inactive. At that point, Grand St.’s site will just be a gallery of content and photos.\nThat’s because the Grand St. team has taken on a lot more projects at Etsy, so from a user experience and maintenance perspective, it made sense to move Grand St. away from commerce, Etsy Senior PR Manager Nicole Summer told TechCrunch.\n“We at Etsy and Grand St. have truly appreciated all the hard work from Grand St. makers, and we welcome them to learn more about joining the Etsy community,” Summer said. “The Grand St. team has become an integral part of the Etsy organization, working on innovative projects to help our sellers scale. We’re grateful to have them on board and excited to continue the work we’re doing to empower our sellers to achieve their creative business goals on their own terms.”\nFor background, Grand St. sells things like solar chargers, a smart light for nighttime bike rides and The Cash Cannon for making it rain. Before the acquisition, Grand St. had raised $1.3 million in seed funding from First Round Capital, David Tisch, Gary Vaynerchuk, betaworks, Collaborative Fund, MESA+, Quotidian Ventures, and Undercurrent.\nFeatured Image: Dennis Skley/Flickr UNDER A CC BY-ND 2.0 LICENSE", 

Вы можете видеть, что они используют \ п в их формате JSON.

+0

Я думаю, что «\ п» (стандартный способ) это хороший способ передать символ новой строки в формате JSON от сервиса и клиента понимает его и разорвать заявление оттуда. – Jayesh

+0

Спасибо :) Проблема заключается в том, что парсеры JSON (jackson) удаляют эти символы из строки (\ n). Любые намеки, как предотвратить это? –

+0

см. Мой ответ ниже, дайте мне знать, если он не работает. – Jayesh

ответ

1

Я также использую Джексон и делаю так, как показано ниже (здесь только вставляется конкретная часть). Для меня все работает, меняйте его в соответствии с вашими потребностями.

@GET 
@Path("/getLocale") 
@Produces({ MediaType.APPLICATION_JSON}) 
public Response getLocale(@Context HttpServletRequest request) { 
    ResponseBuilder responseBuilder = Response.status(200); 

    String str=null; 
    byte[] bytes=null; 

    String appLocation = SystemParameters.getInstance().getParameter("application.home.dir")+"/WEB-INF/lang/"; 

    InputStream is = new FileInputStream(appLocation+"/en_US.json"); 

    try { 
     bytes = IOUtils.toByteArray(is); 
    } catch (IOException e) { 
     //ERROR 
    } 

    str = new String(bytes, "UTF-8"); 
    str = str.replaceAll("\\r\\n", ""); 
    str = str.replaceAll("\\t", ""); 
    str = str.replaceAll("\\\"", "\""); 

    return responseBuilder.entity(str).build(); 
} 

JSON файл:

"CERTIFICATE_STATUS_PASSWORD_INVALID":"Unable to read certificate with the given password.\nUpload the certificate with a valid password." 
+0

Спасибо! Попробуем это позже и вернемся к вам. –

+0

Это работает - я просто подумал, что перехватчик может стать отличным способом справиться с этим! Как вы думаете? –

Смежные вопросы