convert string ["string"] to string array - java

I have a kind of strange problem, I am receiving from server side an compressed text that is a string array, for exemple ["str1","str2"] or just ["str"]
Can I convert it to an normal string array? like:
String[] array;
array[1] = "str";
I know that is not a big deal to convert an simple string but not this one...Any ideas?

This text can be treated as JSON so you could try using JSON parser of your choice. For gson your code could look like.
String text = "[\"str1\",\"str2\"]"; // represents ["str1","str2"]
Gson gson = new Gson();
String[] array = gson.fromJson(text, String[].class);
System.out.println(array[0]); //str1
System.out.println(array[1]); //str2
If you are able to change the way server is sending you informations you can consider sending array object, instead of text representing array content. More info at
https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html
http://www.tutorialspoint.com/java/java_serialization.htm
or many other Java tutorials under serialization/deserialization.

This may help you:
// cleanup the line from [ and ]
String regx = "[]";
char[] ca = regx.toCharArray();
for (char c : ca) {
line = line.replace("" + c, "");
}
String[] strings = line.split("\\s*,\\s*");
// now you have your string array

Related

Getting simple Json string from url and converting it to String[] Android

I am trying to pull Json string from url and put it into String[] inside my android application.
String i am getting from my url is "[\"What is your name?\",\"How do you do?\"]"
I am trying to create Quizz class in my app where i want to call constructor and then it pull data from url and put it into private variables.
I have tried many things but getting multiple errors (with network and other stuff) and now i am somewhere with async tasks where i got lost and think i am going totally wrong way.
Class i want to have is like this:
public class Quizz {
private String[] Questions;
public Quizz() {
// Here i want to load data from url into variable Questions
}
public String getQuestion(int id) {
return "Not implemented!";
}
}
And when i create Quizz object in my main activity i want to have questions loaded.
you can use the following article to help you decode your json
Article Link
Also, You can use JSONArray in the Following Article
Use Retrofit to Connect to API, and Use its converter to deserialize the JSON Response.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
it's very effective and has error handling built into it.
I know you are looking for a string[] array but in this case its best to use a arraylist as sizes can change when retrieving the response.
//create empty strings arraylist
List<String> strings = new Arraylist<>()
//try parse the response as a JSONarray object
try{
//get url string response as a json array
JSONArray jsonArray = (JSONArray) urlStringResponse;
//parse through json array and add to list
for(int i = 0; i < jsonArray.length(); i++){
String str = (String) jsonArray.getJSONObject(i);
strings.add(str);
}
} catch (JSONException e) {
Log.e("JSON", "Problem parsing the JSON results", e);
}
What about to use String.split() method?
val string = "[\"What is your name?\",\"How do you do?\"]"
val split: List<String> = string.subSequence(1, string.length - 1).split(',')
val array = split.toTypedArray()
array.forEach { println(it) }
And result will be
"What is your name?"
"How do you do?"

Using Gson to serialize strings with \n in them

\n in a string is effective in printing the text following \n in next line. However, if the same string is serialized using Gson, then \n is no more effective in printing it in next line. How can we fix this ? Sample program given below.
In the program below, output of toString on map is printing text in next line due to presence of \n. However, the json string serialized using Gson is not able to show the same behaviour. In serialized string i.e. gsonOutput variable, '\' and 'n' are getting treated as separate characters, due to which the text after \n is not getting printed in next line. How can we fix this in gson serialization ?
Program:
Map<String, String> map = new HashMap<String,String>();
map.put("x", "First_Line\nWant_This_To_Be_Printed_In_Next_Line");
final String gsonOutput = new Gson().toJson(map);
final String toStringOutput = map.toString();
System.out.println("gsonOutput:" + gsonOutput);
System.out.println("toStringOutput:" + toStringOutput);
Output:
gsonOutput:{"x":"First_Line\nWant_This_To_Be_Printed_In_Next_Line"}
toStringOutput:{x=First_Line
Want_This_To_Be_Printed_In_Next_Line}
I am guessing that the gsonOutput has escaped the new line so if you change the line
final String gsonOutput = new Gson().toJson(map);
to (to unescape it):
final String gsonOutput = new Gson().toJson(map).replace("\\n", "\n");
you will get the output
gsonOutput:{"x":"First_Line
Want_This_To_Be_Printed_In_Next_Line_With_A_Tab_Before_It"}
toStringOutput:{x=First_Line
Want_This_To_Be_Printed_In_Next_Line_With_A_Tab_Before_It}
There probably is a better way of doing this :-)

cant convert json string to regular string array in java

iam trying to convert this json string back to an array but i can't seem to do it
["\"abba\"","\"repaper\"","\"minim\"","\"radar\"","\"murdrum\"","\"malayalam
\"","\"turrut\"","\"navan\""]
can anyone help, or point me in the right direction of some tutorials. Ive tried split(",") etc but im really not too sure how to extract the words themselves.
client code:
Gson gson;
String[] words = { "hello", "Abba", "repaper", "Minim", "radar",
"murdrum", "malayalam", "cheese", "turrut","Navan" };
gson = new Gson();
String json = gson.toJson(words);
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client
.resource("http://localhost:8090/RestSampleApp/rest/webservice/returnarray");
ClientResponse response = service.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, json);
String output = response.getEntity(String.class);
//String target2 = gson.fromJson(json, String.class);
System.out.println(output);
webservice code:
#POST
#Path("returnarray")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String returnstuff(String list) {
list2 = list.substring(1, list.length() - 1); //gets rid of "[]"
temp = new ArrayList<String>(Arrays.asList(list2.split(",")));
Algorithim algo = new Algorithim(temp); // instance of algorithim class takes in arrayList
algo.getpalindromesarray(); //creates plaindrome arraylist
newlist = algo.getnewlist();
String details = gson.toJson(newlist);
return details;
}
EDIT: My previous answer wasn't correct, see this new one...
You are not using Gson correctly... You are serializing the objects well, but you're not doing a correct deserialization... I suggest you to take a brief look to Gson documentation, it's few lines and you'll understand it better...
First you serialize your array correctly in your client, with:
String json = gson.toJson(words);
Then you send it using Jersey API, I think that it's correct (although I'm not an expert in Jersey...)
Then your problem is that you are not deserializing the JSON correctly in your web service. You should parse the JSON string passed as a parameter, and you can do it with Gson as well, like this:
Gson gson = new Gson();
Type listOfStringsType = new TypeToken<List<String>>() {}.getType();
List<String> parsedList = gson.fromJson(list, listOfStringsType);
Now you can do whatever you want with your list of words working with a proper Java List.
Once you finish your work, you serialize again the List to return it, with:
String details = gson.toJson(parsedList);
Now you have to repeat the deserializing operation in your client to parse the response and get again a List<String>...
Note: You should never try to do things like serialize/deserialize JSON (or XML...) manually. A manual solution may work fine in a particular situation, but it can't be easily adapted to changes, thus, if your JSON responses change, even only slightly, you'll have to change a lot of code... Always use libraries for this kind of things!
You'd better use json library, e.g. Jackson. If code yourself, you can do like below:
// 1st: remove [ and ]
s=s.substring(1, s.length()-1);
// 2nd: remove "
s=s.replaceAll("\"\"", "");
// 3rd: split
String[] parts = s.split(",");
You can try to use String.format to specify the format you waant to pass as part of your request.
For Ex :
WebResource webResource = client.resource("http://localhost:8090/RestSampleApp/rest/webservice/returnarray");
String input = String.format("{\manual format "}",parameter);
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
This is how I have acheived my goal

Dynamic String get dynamic image name in java

i have a dynamic String like
age/data/images/four_seasons1.jpg
from above string i need to get the image name alone (i.e.) four_seasons1.jpg
the path and the image will be a dynamic one(any image format will occure)
Please let me know how to do this in java?
thanks in advance
Use the File Object.
new File("/path/to/file").getName()
You could also use String.split().
"/path/to/file/sdf.png".split("/")
This will give you an array in which you pick the last element. But the File Object is better suited.
String text = "age/data/images/four_seasons1.jpg";
String name = text.substring(text.lastIndexOf("/") + 1);
String path = text.substring(0, text.lastIndexOf("/"));
System.out.println(name);
System.out.println(path);
Outputs
four_seasons1.jpg
age/data/images
Take some time and become familiar with the java.lang.String API. You'll be doing this kind of stuff a lot
You can go for regex but if you find the pattern is fixed, A very crude solution can be a straight forward approach
String url = "age/data/images/four_seasons1.jpg";
String imageName = url.substring(url.lastIndexOf( "/" )+1, url.length()) ;
You can parse this path. As a delimiter you must take '/' symbol. After that you can take last parsed element.
String phrase = "age/data/images/four_seasons1.jpg";
String delims = "/";
String[] tokens = phrase.split(delims);
About String.split you can read more here.
String s = "age/data/images/four_seasons1.jpg";
String fileName = new String();
String[] arr = s.split("/");
fileName = arr[arr.length-1];
}

How do I convert a string with 'hashtags' to json in java?

I have a String in java that might look like this:
String str = "Hello this is #David's first comment #excited"
I want to convert this string to a json object, but it throws an error when I use the below:
JSONObject json = new JSONObject(str);
I have found out that it throws an error due to the '#' symbol.
Is there any other way to convert the string to json, without much hassle ?
The problem is not so much the '#' symbols; it's that you are trying to parse the string as if it's already JSON. You probably want something like this:
JSONObject json = new JSONObject();
json.put("firstString", str);
String jsonString = json.toString();
or, more briefly (if all you want is a quoted JSON string:
String jsonString = JSONObject.valueToString(str);

Categories

Resources