Convert String array to string back to string array - java

I converted a string array to string using Arrays.toString(variable) and saved it in a session. Now I want to convert it back to a string array. How do I do that?
I was hoping if there's a way to do it in a simpler way, like parsing it to string array.
Here's a sample of the string. It is separated by a comma.
[Any, Resolved (1), ANS MACH / LEFT MSG (1)]
Update:
I've been advised not to use toString to serialize array. But since I'm dealing with simple array, I still opted to use it.

If the individual strings might themselves include a comma followed by a space, then this would not be feasible. Multiple String[] arrays could map to the same flat String, and an inverse function would not exist.
However, you note in a comment that your strings cannot include the comma separator. You can split the flat string back into the original substrings, using ", " (comma,space) as a separator.
APIs that support this include the standard Java String.split() method, and Guava's Splitter class.
Here's an example with Java's split() method:
public static void main(String[] args) {
String[] strs = new String[] { "Foo", "Bar", "Baz" };
String joined = Arrays.toString( strs );
String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);
// String.split()
String[] resplit = joinedMinusBrackets.split( ", ");
for ( String s : resplit ) {
System.out.println( s );
}
}
And here's an example with Guava's Splitter class:
public static void main(String[] args) {
String[] strs = new String[] { "Foo", "Bar", "Baz" };
String joined = Arrays.toString( strs );
String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);
// Guava Splitter class
List<String> resplitList = Splitter.on( ", " ).splitToList( joinedMinusBrackets );
for ( String s : resplitList ) {
System.out.println( s );
}
}

I guess that's the answer you're searching for. Briefly, it's about using serialization with apache codecs for encoding/decoding objects. I don't want to do copy/paste from another answer, so I'll give you only the code sample in case link changes someday.
Here it is:
// serialize
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(yourArray);
//encode
String encodeString = new String(Hex.encodeHex(out.toByteArray()));
// deserialize
ByteArrayInputStream in = new ByteArrayInputStream(Hex.decodeHex(yourString.toCharArray()));
String yourArray = Arrays.toString((String[]) new ObjectInputStream(in).readObject());
}
// And then you could use `String#split()` method to convert string to array.
Another option is to use something like Gson JSON library, with Gson, you can convert any java object to a json string and then convert it back. Example code may looks like this:
//Put an array (or any other object to gson object
Gson gson = new Gson();
String json = gson.toJson(yourArray);
// Retrieve your object from gson
Gson gson = new Gson();
Array array = gson.fromJson(json, Array.class);
For more details you look this article.

Simplest solution (assuming that we are talking about Java EE's HttpSession) would be not placing String representing array, but array itself via setAttribute(String name, Object value) so as you see value can be any Object, not only String.
DEMO using List<String> instead of String[] (may not be perfect but should get the idea):
#WebServlet("/SessionDemo")
public class SessionDemo extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
List<String> list = (List<String>) session.getAttribute("list");
printList(out, list);
printForm(out);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
List<String> list = (List<String>) session.getAttribute("list");
if (list == null){
list = new ArrayList<>();
session.setAttribute("list", list);
}
list.add(request.getParameter("item"));
printList(out, list);
printForm(out);
}
private void printList(PrintWriter out, List<String> list) {
out.println("current items:");
if (list != null){
out.println("<ul>");
for (String item : list){
out.append("<li>").append(item).println("</li>");
}
out.println("</ul>");
}else{
out.println("list is empty");
}
out.println("<hr/>");
}
private void printForm(PrintWriter out){
out.println(
"<form action='./SessionDemo' method='post'>"
+ "<input type='text' name='item'/>"
+ "<input type='submit' value='add to list'/>"
+ "</form>"
);
}
}

If you always wants string operation with this kinda sting split() is what you need:
public static void main(String []args){
String string = "[Any, Resolved (1), ANS MACH / LEFT MSG (1)]";
String[] parts = string.split(",");// your string Array
int i=0;
for(; i< parts.length; i++)
System.out.println(parts[i]);
}
If your string contains [ and ] also. Then you would need .replace()
Best practice to use JSON for Response/Request processing.

Related

Read File into ArrayList from .txt file on begging of program

So i got a Java Class of Konto, which got:
private String navn;
private int medlemdsnummer;
private String årstal;
private String måned;
private String dag;
LocalDate localDate;
They are used like this:
ArrayList<Konto> kontoArrayList = new ArrayList<>();
And I save my ArrayList to a .txt document before the program shutdowns:
private static void saveToFile(ArrayList<Konto> kontoArrayList) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("medlemmer.txt")));
PrintStream printStream = new PrintStream("medlemmer.txt");
for (int i = 0; i < kontoArrayList.size(); i++) {
printStream.println(content + kontoArrayList.get(i).getMedlemdsnummer() + ": " + kontoArrayList.get(i).getNavn() + " " +
kontoArrayList.get(i).getLocalDate());
}
}
They end up looking like this in the .txt file:
1: Kasper 1996-11-20
2: Jonas 1996-04-27
3: Jesper 1996-05-14
Okay, so far so good. Now for the question: When the program is turned on, I want to make it able to load the .txt file from the beginning and "transfer" it to an ArrayList of Konto. So that i later can use my method (addNewMember). I saw a lot of example on the internet, but they all use:
ArrayList<String> somename = new ArrayList<String>();
I want to use:
ArrayList<Konto> konto = new ArrayList<Konto>();
Is this possible, if so how do to?
If not what could i do instead?
Thanks in advance, Victor.
You can read all lines from the file as string and split this strings by spaces.
And then create new objects with parsing of options.
Something like this:
List<String> strings = Files.readAllLines(Paths.get("test.txt"));
List<Konto> kontos = new ArrayList<>();
for (String string : strings) {
String[] data = string.split(" ");
kontos.add(new Konto(data[1], new Date(data[2])));
}
Or using Streams:
List<Konto> kontos = Files.lines(Paths.get("test.txt")) // String
.map(line -> line.split(" ")) // String[]
.map(data -> new Konto(data[1], new Date(data[2])) // Konto
.collect(Collectors.toList());
Something like the following, you've got to check it
class TestParse {
public TestParse(String line) {
StringTokenizer tokenizer = new StringTokenizer(line, ",");
if(tokenizer.countTokens() != 3) {
throw new RuntimeException("error");
}
s1 = tokenizer.nextToken();
s2 = tokenizer.nextToken();
s3 = tokenizer.nextToken();
}
private String s1;
private String s2;
private String s3;
}
public class TestRead {
public static void main(String[] args) throws Exception {
List<TestParse> testParses = new ArrayList<TestParse>();
BufferedReader in = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = in.readLine()) != null) {
testParses.add(new TestParse(line));
}
in.close();
}
}
I think one way you can try is read line by line, and define a Konto constructor that accept a string.
Edit: You can follow the below answer from Lucem. But I think I will do it a little different
List<String> strings = Files.readAllLines(Paths.get("fileName.txt"));
List<Konto> kontos = new ArrayList<>();
for (String s: strings) {
kontos.add (new Konto(s))
}
or using Streams:
List<Konto> kontos = Files.lines(Paths.get("fileName.txt"))
.map(line -> new Konto(line));
.collect(Collectors.toList());
And then in Konto class add a constructor that accept a string and manipulate it. Because you didn't add the class Konto here, I didn't know the exact name of your properties, so I let it be "yourPropertyNumber", "yourPropertyString" and "yourPropertyDate"
class Konto {
public Konto (String input) {
// Split based on white space
String[] dataParts = input.split(" ");
// Get rid of the semicolon
String number = dataParts[0].substring(0, dataParts[0].length - 1);
yourPropertyNumber = parseInt(number);
yourPropertyString = dataParts[1];
yourPropertyDate = new Date(dataParts[2]);
}
// Your other code here
}
The reason I want to pass a String to a constructor rather than parse the string where I read the file is that I think it is easier to debug or make change in the way it reads the string.
Hope this help.

Correctly convert String array to String and back in java

I have a following code:
String[] stringArray = new String[] { "One,", "Two", "Three" };
System.out.println(Arrays.toString(stringArray));
which produces the following string:
[One,, Two, Three]
Right now It is impossible to convert this string back into the same String[] with 3 elements because of two consecutive commas ,,
How to correctly make this conversion ?
UPDATED
Arrays.toString(stringArray)
is just a particular case and I'm not limited to use only this approach. I need to implement approach where conversion from String[] to String and back from String to String[] will be idempotent operation.
You state that "Arrays.toString is absolutely not required."1
I suggest you serialize the Array to Base64:
public String serializeArray(final String[] data) {
try (final ByteArrayOutputStream boas = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(boas)) {
oos.writeObject(data);
return Base64.getEncoder().encodeToString(boas.toByteArray());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Then deserialize the Base64 to an array:
public String[] deserializeArray(final String data) {
try (final ByteArrayInputStream bias = new ByteArrayInputStream(Base64.getDecoder().decode(data));
final ObjectInputStream ois = new ObjectInputStream(bias)) {
return (String[]) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
This requires Java 8.
Example:
public static void main(String args[]) throws Exception {
String[] stringArray = new String[]{"One,", "Two", "Three"};
String serialized = serializeArray(stringArray);
String[] deserialized = deserializeArray(serialized);
System.out.println(Arrays.toString(stringArray));
System.out.println(serialized);
System.out.println(Arrays.toString(deserialized));
}
Output
[One,, Two, Three]
rO0ABXVyABNbTGphdmEubGFuZy5TdHJpbmc7rdJW5+kde0cCAAB4cAAAAAN0AARPbmUsdAADVHdvdAAFVGhyZWU=
[One,, Two, Three]
Note, this works for any Object that implements Serializable, not just String[].
As a simple alternative, you could replace , by \, before joining the array and then also replace \, by , after splitting it. This relies on the standard "escaped delimiter" pattern that CSV uses. But it will fail if the user inputs \, somewhere in the input, so is less robust: YMMV.
public String serializeArray(final String[] data) {
return Arrays.stream(data)
.map(s -> s.replace(",", "\\,"))
.collect(joining(","));
}
public String[] deserializeArray(final String data) {
return Pattern.compile("(?<!\\\\),").splitAsStream(data)
.map(s -> s.replace("\\,", ","))
.toArray(String[]::new);
}
Convert it to a format intended for this, like JSON. Using Jackson it would be something like this:
ObjectMapper objectMapper = new ObjectMapper();
String out = objectMapper.writeValueAsString(Arrays.asList(array));
And back:
List<String> strings = (List<String>) objectMapper.readValue(out, List.class);
String[] array2 = strings.toArray();
I really don't know what you want to do, but the array separator , is in your string, so the simplest way to avoid this would be to avoid building the string with default array separator! like this:
String[] stringArray = new String[] { "One,", "Two", "Three" };
StringBuilder string = new StringBuilder();
string.append("[");
for (int i = 0; i < stringArray.length; i++) {
string.append(stringArray[i] + (i == (stringArray.length - 1) ? "" : "; "));
}
string.append("]");
System.out.println(string);
System.out.println(string.toString().substring(1, string.length() - 1).split("; "));
surely you can do some more stuff do get it work with default array separator, but it depends on what you want to do, I just choose the simplest way.

Getting "geometry" from google API result

So far with the code I have, I am able to get results as a JsonObject. However, I am trying to get the coordinates of the location based on the postal code that I have entered. How can I retrieve the "lat" and "lng" as Strings/JsonElements? Would really appreciate if you can give me some insight. Thanks!
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
//the JSON builder
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String restaurant = request.getParameter("r");
String customer = request.getParameter("c");
//Get coordinates of the restaurant
String longLatApi = "https://maps.googleapis.com/maps/api/geocode/json?address=" + restaurant;
URL url = new URL(longLatApi);
URLConnection connection = url.openConnection();
connection.addRequestProperty("Referer", longLatApi);
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
String jsonString = builder.toString();
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
out.println(gson.toJson(obj));
JsonElement and its subclasses have nice methods to iterate through JSON elements of different kinds: null, a primitive (numbers, string literals, and booleans), a JSON object, or a JSON array. Knowing an exact structure of the response JSON document, you can extract child elements pretty straight-forward:
final URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=Greenwich");
// Let Gson parse the JSON input stream without expensive intermediate strings
try ( final Reader reader = new BufferedReader(new InputStreamReader(url.openStream())) ) {
final JsonParser jsonParser = new JsonParser();
// Extract the `results` array
final JsonArray resultsJsonArray = jsonParser.parse(reader)
.getAsJsonObject()
.get("results")
.getAsJsonArray();
// Iterate over each result array element
for ( int i = 0; i < resultsJsonArray.size(); i++ ) {
final JsonObject resultJsonObject = resultsJsonArray.get(i).getAsJsonObject();
System.out.println(resultJsonObject.getAsJsonPrimitive("formatted_address").getAsString());
// Picking up the `geometry` property as a JSON object
final JsonObject geometryJsonObject = resultJsonObject.get("geometry").getAsJsonObject();
// And dumping the location
final JsonObject locationJsonObject = geometryJsonObject.get("location").getAsJsonObject();
dumpLocationJsonObject("Location", locationJsonObject);
final JsonElement boundsJsonElement = geometryJsonObject.get("bounds");
// There can be a `bounds` object with two additional properties
if ( boundsJsonElement != null && !boundsJsonElement.isJsonNull() ) {
final JsonObject boundsJsonObject = boundsJsonElement.getAsJsonObject();
dumpLocationJsonObject("North/East", boundsJsonObject.get("northeast").getAsJsonObject());
dumpLocationJsonObject("South/West", boundsJsonObject.get("southwest").getAsJsonObject());
}
}
}
private static void dumpLocationJsonObject(final String name, final JsonObject location) {
final double latitude = location.getAsJsonPrimitive("lat").getAsDouble();
final double longitude = location.getAsJsonPrimitive("lng").getAsDouble();
System.out.println("\t" + name + ": (" + latitude + "; " + longitude + ")");
}
The output:
Greenwich, London SE10, UK
Location: (51.48257659999999; -0.0076589)
As an alternative approach, you can define custom JSON to Java classes mappings in order to deserialize the JSON document as a custom class instance, and not just JsonElement (something like gson.fromJson(reader, customType)). Both approaches have pros and cons.

How to convert Stringified array to ArrayList in Android

I am getting this from server
"[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]"
The above text is not an array, but a string returned from server.
I want to convert this in an ArrayList
Is there a way to convert it?
There is no good idea to manually parse that string. You should use a library that parses JSON strings for you. Anyhow the given string is not a valid JSON string and like others have mentioned you should request JSON formatted data from the server.
If your server only returns like this and you need to manually parse then this would be a solution. Not a very good one, but it does the job.
public static void main(String[] args) {
List<String> words = new ArrayList<>();
String string = "[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
String withoutBrackets = string.replaceAll("[\\[\\](){}]", ""); // Remove all the brackets
for (String word : withoutBrackets.split(",")) {
String singleWord = word.replaceAll("\"", "");
words.add(singleWord);
}
System.out.println(words);
}
Can be done using separator, where s is String:
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
Try using Gson. Add this to your gradle
compile 'com.google.code.gson:gson:2.2.4'
Hope this helps -
String str = "[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
Gson gson=new Gson();
ArrayList<String> strings = gson.fromJson(str,new TypeToken<ArrayList<String>>(){}.getType());
This will work
String text = [\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
text = text.replaceAll("[\\[\\](){}\"]", "");
List<String> list = Arrays.asList(text.split(","));
Modify your String using
str = str.replace ("[", "").replace ("]", "");
so it is the same as
String str = "\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"";
then use
List<String> al = new ArrayList<String>(Arrays.asList(str.split(",")));
System.out.println(al);
This is the correct way to parse JSON String to ArrayList :)
ArrayList<String> list = new ArrayList<String>();
String newArrayy ="[\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqr\",\"stu\",\"vwx\",\"yz\"]";
imagePath = newArrayy;
try {
JSONArray jsonArray = new JSONArray(imagePath);
if (null != jsonArray) {
Logger.LogError("imagePathhh", jsonArray.toString() + "" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
String value =(String) jsonArray.getString(i);
list.add(value); dataBaseCurdOperation.insertPaymentPath(jsonArray.getString(i));
}
} else {
}
} catch (Exception e) {
}
}
Sanjay in his answer pointed it out correct , that it is not correct format.
Still if you are using Gson library to parse JSON data, then the following method take care of this format also. So you have no need to do anything :)
new Gson().fromJson(your_server_response, Model.class);
One more way to do this is using java's inbuilt method
public String replaceAll (String regularExpression, String replacement)

Remove json object from json array

I've a JsonArray like:
"fields" : [
{
"name":"First Name",
"id":1
},
{
"name":"Middle Name",
"id":2
},
{
"name":"Last Name",
"id":3
}
]
I want to remove second JsonObject from above JsonArray. In order to do that I' wrote following code:
JsonArray fieldsObject =jsonObject.getJsonArray("fields");
fieldsObject.remove(fieldsObject.getJsonObject(2));
But second line throws error: java.lang.UnsupportedOperationException
Is there any way, I can remove JsonObject from a JsonArray?
You can not remove element from JsonArray as it does not support remove() method:
private static final class JsonArrayImpl extends AbstractList<JsonValue> implements JsonArray {
And remove() method's implementation comes from AbstractList :
public E remove(int index) {
throw new UnsupportedOperationException();
}
Instead why don't you create a separate data strucure array or list to hold the objects that you want?
By the way, the purpose of using JsonArray is to load json data in object form that is why it supports read methods but does not support modifications on the loaded data structure.
May be Your JsonElement or JSONArray is null.
getJsonObject returns a JSONObject.
the remove method want int.
UnsupportedOperationException
if removing is not supported.
Try This :
JSONArray fieldsObject =jsonObject.getJsonArray("fields");
fieldsObject.remove(int index);
OR
JSONArray result = new JSONArray();
for(int i=0;i<fieldsObject.length();i++)
{
if(i!=2)
{
result.put(fieldsObject.get(i));
}
}
and assign result to original one
fieldsObject=result;
gson library
Remove works for gson library version 2.3.1
public static void main(String[] args) throws Exception {
String s = "{ \"fields\" : [ "+
" {\"name\":\"First Name\",\"id\":1},"+
"{\"name\":\"Middle Name\",\"id\":2},"+
"{\"name\":\"Last Name\",\"id\":3}"+
"]}";
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(s).getAsJsonObject();
System.out.println("original object:"+json);
JsonArray fieldsObject = json.getAsJsonArray("fields");
System.out.println("Before removal :"+fieldsObject);
Object remove = fieldsObject.remove(1);
System.out.println("After removal :"+fieldsObject);
}
Output:
original object:{"fields":[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]}
Before removal :[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]
After removal :[{"name":"First Name","id":1},{"name":"Last Name","id":3}]
org.json library
Remove works for org.json library
public static void main(String[] args) throws Exception {
String s = "{ \"fields\" : [ "+
" {\"name\":\"First Name\",\"id\":1},"+
"{\"name\":\"Middle Name\",\"id\":2},"+
"{\"name\":\"Last Name\",\"id\":3}"+
"]}";
JSONObject json = new JSONObject(s);
System.out.println("original object:"+json);
JSONArray fieldsObject =json.getJSONArray("fields");
System.out.println("Before removal :"+fieldsObject);
Object remove = fieldsObject.remove(1);
System.out.println("After removal :"+fieldsObject);
}
Output:
original object:{"fields":[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]}
Before removal :[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]
After removal :[{"name":"First Name","id":1},{"name":"Last Name","id":3}]
I tried using org.json library as mentioned by Sanj in the above post. We can remove the element from JSONArray as below. I placed the json content in the .txt file and read into the String object for constructing the JSONObject. Please refer the code below.
public class App{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
String jsonContent = "";
String jsonLine;
while((jsonLine=br.readLine())!=null){
jsonContent+=jsonLine;
}
JSONObject jObj = new JSONObject(jsonContent);
JSONArray jsonArray = jObj.getJSONArray("fields");
jsonArray.remove(1);
System.out.println(jsonArray);
}
}

Categories

Resources