I have a String like this:
String content = "{"begin"bf3b178a70.jpg","end",....},{"id":,"f06190e8938.jpg","end",....}"
and i want to cut out the image ID like this:
bf3b178a70.jpg
f06190e893.png
and after that, i want compose the image ID with a new url like this:
url.com/image/bf3b178a70.jpg
url.com/image/f06190e893.png
I begin with substring() to cut the first part and with content.split(""id":,"); but i have problems with a string array and normal string. I used the string array with a for-loop, because the real string is very long.
Will someone please help me?
At first blush, it looks like your string is formatted as JSON. If that's the case you can use the JSON.org Java parser or one of the many other parsers listed on the JSON.org site to break it down, or just follow the syntax diagrams they give; simple string-chopping is inadvisable since JSON is not a regular language.
I'm going to assume for the moment that you're receiving a JSON array-of-objects (square brackets around, comma separated), and that you are either reading from a file or a Web service, either of which provides an InputStream. If you have something else, you can pass a Reader or a plain String to the JSONTokener constructor, or if you have a byte array you can wrap it in a ByteArrayInputStream and pass that in.
I don't have a JDK handy to even check if this compiles :-) but here goes.
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import org.json.*;
public class ImageListProcessor
{
public static ArrayList<URL> processList(InputStream toProcess, URL baseURL)
throws JSONException, MalformedURLException
{
JSONTokener toProcessTokener = new JSONTokener(toProcess);
JSONObject toProcessResponse = new JSONObject(toProcess);
if (!toProcessResponse.isNull("error")) {
// it's an error response, probably a good idea to get out of here
throw new JSONException("Response contains error: " + toProcessResponse.get("error"));
}
JSONArray toProcessArray = toProcessResponse.getJSONArray("items");
int len = toProcessArray.length();
ArrayList<URL> result = new ArrayList<URL>(len);
for(int i = 0; i < len; i++) {
JSONObject imageRecord = toProcessArray.getJSONObject(i);
String imagePath = imageRecord.getString("image");
// if you want to remove the date portion of the path:
imagePath = imagePath.substring(1 + imagePath.lastIndexOf('/'));
URL combinedURL = new URL(baseURL, imagePath);
result.add(combinedURL);
}
return result;
}
}
Try something like this:
import java.util.regex.*;
public class ReplaceDemo {
public static void main(String[] args) {
String input =
"User clientId=23421. Some more text clientId=33432. This clientNum=100";
Pattern p = Pattern.compile("(clientId=)(\\d+)");
Matcher m = p.matcher(input);
StringBuffer result = new StringBuffer();
while (m.find()) {
System.out.println("Masking: " + m.group(2));
m.appendReplacement(result, m.group(1) + "***masked***");
}
m.appendTail(result);
System.out.println(result);
}
}
Related
I have one text file. I have to read contents between two given patterns.
for example lets I have a file names - datafromOU.txt
I have to need data from the pattern1 till pattern2.
pattern1 : "CREATE EXTR"
Pattern2 :";"
But problem is - file has multiple occurances of pattern2. So my requirement is to look for pattern1 and then search immediate occurance of pattern2 after the pattern1. I need to store this into one string and then process later.
Can you help me how to read data from pattern1 and immediate occurance of pattern2 into a string variable using java streams?
I use java8. Thanks a lot in advance.
Thanks.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main {
static String getPatternFromString(String startPattern,String endPattern,String data) {
int startIndex=data.indexOf(startPattern);
data=data.substring(startIndex);
int endIndex=data.indexOf(endPattern, startIndex + startPattern.length());
data=data.substring(0,endIndex+1);
return data;
}
public static void main(String[] args) throws IOException {
File file1 = new File("C:\\Users\\amish\\Desktop\\partie.txt");
String startPattern="CREATE EXTR";
String endPattern=";";
try (BufferedReader leBuffer1 = new BufferedReader(new FileReader(file1));) {
StringBuilder everything = new StringBuilder();
String line;
while ((line = leBuffer1.readLine()) != null) {
everything.append(line);
}
String data = everything.toString();
data = data.trim();
System.out.println(data);
System.out.println(getPatternFromString(startPattern,endPattern, data));
leBuffer1.close();
} catch (FileNotFoundException exception) {
System.out.println("File not found");
}
}
}
I have a question, because I am new to Bing Search API and I am not familiar how to use it. I am trying to get all the links from the Bing search result. So I am searching for keyword. Is working but I want to get the links of the results that I got from the Bing Search API that I have included in my Java application. The problem is that I want to retrieve and save the links into an array. So I am using XML to parse it to JSON. But the main problem when i am trying to get the Urls or links I cannot get them. Does anyone has an idea how to do it or where I am doing it wrong?
I want for example to get http://en.wikipedia.org/wiki/Omonoia (one of the search results of Bing search API)
Here is some of the code:
String str = "http://maps.google.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
URL url = new URL(str);
InputStream is = url.openStream();
int ptr = 0;
StringBuilder builder = new StringBuilder();
while ((ptr = is.read()) != -1) {
builder.append((char) ptr);
}
String xml = builder.toString();
JSONObject jsonObject = XML.toJSONObject(xml);
System.out.println(jsonObject.toString());
System.out.println(jsonObject.get("id"));
some of the output:
"feed":{"entry":[{"id":"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=' what is omonoia'&$skip=0&$top=1","title":{"type":"text","content":"WebResult"},"updated":"2015-01-15T14:35:57Z","content":{"m:properties":{"d:Url":{"content":"http://en.wikipedia.org/wiki/AC_Omonia","m:type":"Edm.String"},"d:DisplayUrl":{"content":"en.wikipedia.org/wiki/AC_Omonia","m:type":"Edm.String"},"d:Title":{"content":"AC Omonia - Wikipedia, the free encyclopedia","m:type":"Edm.String"},"d:Description":{"content":"Athletic Club Omonoia Nicosia, commonly referred to as Omonoia, is a Cypriot professional football club based in the capital city, Nicosia. The club was established ...","m:type":"Edm.String"},"d:ID":{"content":"88cf85ab-f077-4f2b-8037-f3d3447b9d34","m:type":"Edm.Guid"}},"type":"application/xml"}},{"id":"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=' what is omonoia'&$skip=1&$top=1","title":{"type":"text","content":"WebResult"},"updated":"2015-01-15T14:35:57Z","content":{"m:properties":{"d:Url":{"content":"http://en.wikipedia.org/wiki/Omonoia","m:type":"Edm.String"},"d:DisplayUrl":{"content":"en.wikipedia.org/wiki/Omonoia","m:type":"Edm.String"},"d:Title":{"content":"Omonoia - Wikipedia, the free encyclopedia","m:type":"Edm.String"},"d:Description":{"content":"Omonoia may refer to: Omonoia Square, one of Athens' main squares, Omonoia Station, the subway station located on the square or Omonoia, the neighborhood around it.","m:type":"Edm.String"},"d:ID":{"content":"4668962f-c8cb-43b1-a12d-19d8aee944bb","m:type":"Edm.Guid"}},"type":"application/xml"}},{"id":"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=' what is omonoia'&$skip=2&$top=1","title":{"type":"text","content":"WebResult"},"updated":"2015-01-15T14:35:57Z","content":{"m:properties":{"d:Url":{"content":"http://wikitravel.org/en/Athens/Omonia","m:type":"Edm.String"},"d:DisplayUrl":{"content":"wikitravel.org/en/Athens/Omonia","m:type":"Edm.String"},"d:Title":{"content":"Athens/Omonia - Wikitravel - The Free Travel Guide","m:type":"Edm.String"},"d:Description":{"content":"Omonia Square is the center of Athens, and is composed of the actual square together with the surrounding streets, open areas and assemblage of grand buildings that ...","m:type":"Edm.String"},"d:ID":{"content":"b711b509-d478-48c4-ad44-51e9d87a5646","m:type":"Edm.Guid"}},"type":"application/xml"}},{"id":"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=' what is omonoia'&$skip=3&$top=1","title":{"type":"text","content":"WebResult"},"updated":"2015-01-15T14:35:57Z","content":{"m:properties":{"d:Url":{"content":"http://www.youtube.com/watch?v=nZfkY7b5vIo","m:type":"Edm.String"},"d:DisplayUrl":{"content":"www.youtube.com/watch?v=nZfkY7b5vIo","m:type":"Edm.String"},"d:Title":{"content":"OMONOIA Vs ANORTHOSI 3-2 - YouTube","m:type":"Edm.String"},"d:Description":{"content":"OMONOIA Vs ANORTHOSI 3-2 - YouTube ... YouTube home","m:type":"Edm.String"},"d:ID":{"content":"a8870310-3a66-493e-9155-3608501305d2","m:type":"Edm.Guid"}},"type":"application/xml"}},{"id":"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=' what is omonoia'&$skip=4&$top=1","title":{"type":"text","content":"WebResult"},"updated":"2015-01-15T14:35:57Z","content":{"m:properties":{"d:Url":{"content":"http://www.youtube.com/watch?v=EOg6rMweu38","m:type":"Edm.String"},"d:DisplayUrl":{"content":"www.youtube.com/watch?v=EOg6rMweu38","m:type":"Edm.String"},"d:Title":{"content":"OMONOIA Vs APOLLON 2-4 - YouTube","m:type":"Edm.String"},"
Some source code I got them from this question: Parsing external XML to JSON in Java?
You can specify the format, so it is not necessary get in XML then parse to JSON. To get JSON just inform $format option in URL, like this:
https://api.datamarket.azure.com/Bing/SearchWeb/Web?Query='what is omonoia'&$format=json
Below an example that retrieves the urls:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
public class BingSearchApiSample {
public static void main(final String[] args) throws Exception {
final String accountKey = "<Your Bing API Key>";
final String bingUrlPattern = "https://api.datamarket.azure.com/Bing/Search/Web?Query=%%27%s%%27&$format=JSON";
final String query = URLEncoder.encode("'what is omonoia'", Charset.defaultCharset().name());
final String bingUrl = String.format(bingUrlPattern, query);
final String accountKeyEnc = Base64.getEncoder().encodeToString((accountKey + ":" + accountKey).getBytes());
final URL url = new URL(bingUrl);
final URLConnection connection = url.openConnection();
connection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
try (final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
final StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
final JSONObject json = new JSONObject(response.toString());
final JSONObject d = json.getJSONObject("d");
final JSONArray results = d.getJSONArray("results");
final int resultsLength = results.length();
for (int i = 0; i < resultsLength; i++) {
final JSONObject aResult = results.getJSONObject(i);
System.out.println(aResult.get("Url"));
}
}
}
}
EDIT: JSON content look like in this link: http://pastebin.com/TcGg6SzN
EDIT: The sample generated the output below:
http://en.wikipedia.org/wiki/AC_Omonia
http://en.wikipedia.org/wiki/Omonoia
http://www.youtube.com/watch?v=XDTjbljYoM8
http://wikitravel.org/en/Athens/Omonia
http://www.youtube.com/watch?v=JwwuQgg3O8o
http://www.omonoia.com.cy/
https://www.omonoia.com.cy/
http://www.athensguide.com/omonia.html
http://wn.com/This_Is_Omonoia
http://www.greece-athens.com/metro/omonoia.php
http://www.encyclo.co.uk/meaning-of-Omonoia
http://www.flickr.com/photos/mascarpone/sets/72157611666181729/
http://pt.wikipedia.org/wiki/Pra%C3%A7a_Omonia
http://en.m.wikipedia.org/wiki/Omonoia,_Athens
http://omonoia.info/
http://www.urbandictionary.com/define.php?term=omonoia
http://www.omonia.org/omonoia/Fair_Play.shtml
https://www.linkedin.com/pub/omonoia-omonoia/11/8b2/695
http://www.ustream.tv/channel/ael---omonoia
http://www.omonia.org/about.shtml
http://www.cyclopaedia.info/wiki/Omonoia
http://www.thisisathens.org/taxonomy/term/15
http://allochiria.bandcamp.com/album/omonoia
http://www.dvbs.eu.org/omonoia/
http://www.facebook.com/pages/omonoia/307148722634077
http://omonoianews.com/
http://www.eurobasket.com/team.asp?Cntry=CYP&Team=1019
http://worddomination.com/omonoia.html
http://www.mixcloud.com/antreas-omonoia/
http://www.newhois.net/www/omonoia.com.cy.html
http://omonoiany.com/html/crete.html
http://vigorito.com.br/codigos/omonoia-fc
http://www.facebook.com/pages/OMONOIA/118545104824439
http://www.cyclopaedia.info/wiki/Omonoia-1
http://www.vipfilefinder.com/download/omonoia/
http://new.livestream.com/accounts/380859
http://www.sevodnya.com/omonoia/
http://www.answers.com/Q/When_was_Omonoia_-_organization_-_created
http://omonoia.com.cubestat.com/
https://twitter.com/eurovison
http://omonoialinks.com/?source=7&date=yes
http://members.tripod.com/antonis_antoniou/season9900/omoapoeE.html
http://www.quickiwiki.com/en/Omonoia,_Athens
https://www.torrentz.com/search?q=omonoia
http://www.omonoia.org/
http://omonoia.com.cy.onlinenoffline.com/
http://omonoia.com.cy.hypestat.com/
http://wn.com/Omonoia__This_Is_My_Life
http://new.livestream.com/accounts/8561914
http://omonoia-nafpaktou.gr.ipaddress.com/
I have this code, which is working fine, that is giving me the source code of a website:
package Quellenpackage;
import java.net.URL;
import java.io.*;
public class Quellcode {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
final String meineURL = "http://www.onvista.de/aktien/technische-kennzahlen/Aareal-Bank-Aktie-DE0005408116";
URL url = new URL(meineURL);
InputStreamReader isr = new InputStreamReader(url.openConnection().getInputStream());
BufferedReader br = new BufferedReader(isr);
// read complete content
String line ="";
String code ="";
while((line = br.readLine()) != null)
{
code += line + "\r\n";
}
// open Reader
br.close();
isr.close();
// give out page content
System.out.println(code);
}
At the moment, this shows me the whole code of the page, but I only want a certain part.
This part should be exactly between this exact signs "Start:" and "ende". So I need something that searches the code for the.. "Start:"
.. part and then gives out everything until the "ende"
I have absolutely no clue whatsoever if this is possible let alone know how to do it. I really hope you guys can help me.
You can use the String.split() method see doku here. Its seperates a String into different Strings at any time the given paremeter is found somewhere in the string.
String[] parts = code.split("Start:"); //makes to parts before Start: and after Start:
parts = parts[1].split("ende"); //makes to parts before ende and after ende
String result = parts[0]; //here is the result
Problem with more than one ende:
If there are more than one ende in the code it wont work this way so you have to choose a different solution where you add the other parts back in:
String[] parts = code.split("Start:");
parts = parts[1].split("ende");
String result = parts[0];
//special case:
//add every splitted sub string, but NOT the last one
for (int i = 1;i<parts.length-1;i++){
result+=parts[i];
}
My bad for the title, I am usually not good at making those.
I have a programme that will generate all permutations of an inputted word and that is supposed to check to see if those are words (checks dictionary), and output the ones that are. Really I just need the last the part and I can not figure out how to parse through a file.
I took out what was there (now displaying the "String words =") because it really made thing worse (was an if statement). Right now, all it will do is output all permutations.
Edit: I should add that the try/catch was added in when I tried turning the file in a list (as opposed to the string format which it is currently in). So right now it does nothing.
One more thing: is it possible (well how, really) to get the permutations to display permutations with lesser characters than entered ? Sorry for the bad wording, like if I enter five characters, show all five character permutations, and four, and three, and two, and one.
import java.util.List;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import static java.lang.System.out;
public class Permutations
{
public static void main(String[] args) throws Exception
{
out.println("Enter anything to get permutations: ");
Scanner scan = new Scanner(System.in);
String io = scan.nextLine();
String str = io;
StringBuffer strBuf = new StringBuffer(str);
mutate(strBuf,str.length());
}
private static void mutate(StringBuffer str, int index)
{
try
{
String words = FileUtils.readFileToString(new File("wordsEn.txt"));
if(index <= 0)
{
out.println(str);
}
else
{
mutate(str, index - 1);
int currLoc = str.length()-index;
for (int i = currLoc + 1; i < str.length(); i++)
{
change(str, currLoc, i);
mutate(str, index - 1);
change(str, i, currLoc);
}
}
}
catch(IOException e)
{
out.println("Your search found no results");
}
}
private static void change(StringBuffer str, int loc1, int loc2)
{
char t1 = str.charAt(loc1);
str.setCharAt(loc1, str.charAt(loc2));
str.setCharAt(loc2, t1);
}
}
If each word in your file is actually on a different line, maybe you can try this:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null)
{
... // check and print here
}
Or if you want to try something else, the Apache Commons IO library has something called LineIterator.
An Iterator over the lines in a Reader.
LineIterator holds a reference to an open Reader. When you have finished with the iterator you should close the reader to free internal resources. This can be done by closing the reader directly, or by calling the close() or closeQuietly(LineIterator) method on the iterator.
The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
it.close();
}
I have JSON which I get from server:
"[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},
{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},
{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele#pele.com\",\"password\":\"\"},
{\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]"
I am using that json and sending to my thread (android thread):
try {
// Method from which I am getting Json described above
String s = dm.getAllUsers();
/*JSONParser jp = new JSONParser();
JsonElement jelement = new JsonParser().parse(s);
JsonArray array1 = jelement.getAsJsonArray();*/
JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i++) {
JSONObject menuObject = array.getJSONObject(i);
// doing something with the object
}
} catch (JSONException e) {
e.printStackTrace();
}
I can not process that Json at all.
I am getting the error "java.lang.String cannot be converted to JSONArray".
A know that problem is caused by "\", and I just do not know how to get rid of "\".
I tried:
1) s.replace("\\", "");
2) s.replace("\"", "'");
3) s.replaceAll("\\", "");
4) s.replaceAll("\"", "'");
In order to erase "\" but replace do not react at all.
I also tried to solve problem with "google-gson-2.2.2" library (code under the comment above, under the method).
Any advice, please?
Try this solution.
s.replaceAll("\\\\", "");
This will definitely work.
Problem has been solved with:
1) s = s.trim();
2) s = s.substring(1, s.length()-1);
3) s = s.replace("\\", "");
My json has been retrieved with "double quotes" on the beginning and on the end. I do not know how string variable can not figure out that "double quotes" is for "beginning" and for "ending" of string.
Thank you everybody for helping.
It is working for me...
In your json the value of "Your Json" is inclused inside "" so it's considered a string not an array..
So the solution is one of two things:
If you can modify the server response, remove the "" from arround the json array. or parse it first as string and then create a json array from that string like..
String notes = jobj.getString("GetNotesResult");
jarray = new JSONArray(notes);
I have no idea why its not working for you. Dot net web services do respond with \ but Java capable of parsing it. I did as below and it worked.
I've coded like this.
JSONArray users = null;
String jsStr = "[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele#pele.com\",\"password\":\"\"}, {\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]";
try {
users = new JSONArray(jsStr);
} catch (JSONException e) {
e.printStackTrace();
}
Log.v("JSONStr", String.valueOf(users.length()));
for(int i = 0; i<users.length(); i++){
try {
Log.v("Name", users.getJSONObject(i).getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
See the LogCat
03-18 16:34:46.459: V/JSONStr(307): 4
03-18 16:34:46.479: V/Name(307): Milos
03-18 16:34:46.479: V/Name(307): Boban
03-18 16:34:46.479: V/Name(307): Pele
03-18 16:34:46.479: V/Name(307): admin
Your json will be valid only if you remove the back slashes () in between. You could use something like:
strJson = strJson.replaceAll("\\\\", ""); OR strJson = strJson.replace("\\", ""); to remove the slashes () in between your json String. Please note that replaceAll() method treats the first argument as a regex, so you must double escape the backslash but, the replace() method treats it as a literal string, so you only have to escape it once. Please have a look at the below example for better understanding: I have kept your json text in a file named json.txt in my hard-drive for demonstration. The contents in the file looks like this:
[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},
{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},
{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele#pele.com\",\"password\":\"\"},
{\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]
Now the code for getting the json array:
package com.stackoverflow.com;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("C:/Users/sarath_sivan/Desktop/json.txt");
BufferedReader br = new BufferedReader(fileReader);
StringBuilder strJsonBuilder = new StringBuilder();
String strLine;
while((strLine = br.readLine()) != null) {
strJsonBuilder.append(strLine);
}
String strJson = strJsonBuilder.toString();
strJson = strJson.replaceAll("\\\\", ""); /*OR you can use strJson = strJson.replace("\\", "");*/
JSONArray jsonArray = new JSONArray(strJson);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject menuObject = jsonArray.getJSONObject(i);
System.out.println("id: " + menuObject.getInt("id"));
System.out.println("name: " + menuObject.getString("name"));
System.out.println("city: " + menuObject.getString("city"));
System.out.println("email: " + menuObject.getString("email"));
System.out.println("password: " + menuObject.getString("password"));
System.out.println();
// do something with your JSON
}
fileReader.close();
} catch (JSONException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
s = s.replace("\\", "");
System.out.println(s);
You need to assign your modified String back to s. This gives a proper parsable JSON.
I don't really like the various String.replaceAll(rexex, "") solutions. What if some of the strings in your JSON contain a \ as part of the information rather than the formatting? I see a 'password' field in your JSON. I don't know whether this is going to be clear text or a hash, but in the case of the former, your program might break if a user uses a backslash in their password.
What you want to do here is unescape a string. This is a problem that as far as I can tell, can't be solved with a simple regex, but it is a problem that has been solved thousands of times before. No need to reinvent the wheel.
How to unescape a string literal in java