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)
Related
I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);
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.
I have json like this
{"First":["Already exists"],"Second":["Already exists"]}
Currently I am doing like
JSONObject jObject = new JSONObject(myJson);
String first = jObject.getString("First")
But I am getting result like this
first = ["Already exists"]
But I want string without square brackets or ""
Try using JSONArray :
JSONArray jArray = new JSONObject(myJson).getJSONArray("First");
String first = jArray.getString(0);
Your json message with key 'first' is Array. So use should treat as Array.
String string = "{'First':['Already exists'],'Second':['Already exists']}";
JSONObject jObject;
try
{
jObject = new JSONObject(string);
Object myJson = jObject.get("First");
if(myJson instanceof JSONArray)
{
JSONArray jArray = jObject.getJSONArray("First");
for (int i = 0; i < jArray.length(); i++)
{
System.out.println("val : "+jArray.getString(i));
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
Thanks to #m.qadhavi i was able to figure out how it works
//This was my temporary solution
//get no. of garage
properties.setPropertyFeaturesGarage(jsonObject
.getJSONObject("extras")
.getString("property_garages")
.replaceAll("[\"]", "")
.replace('[',' ')
.replace(']',' '));
But after going through #m.qadhavi explanation i corrected my code
//get land size
properties.setPropertyFeaturesLandSize(jsonObject
.getJSONObject("extras")
.getJSONArray("property_size")
.getString(0));
Happy Coding
Try to get Substring like e.g.
String first = jObject.getString("First")
String subFirst = first.substring(2,first.length()-2);
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.
I have this code:
BufferedReader br =new BufferedReader(new FileReader("userdetails.txt"));
String str;
ArrayList<String> stringList = new ArrayList<String>();
while ((str=br.readLine())!=null){
String datavalue [] = str.split(",");
String category = datavalue[0];
String value = datavalue[1];
stringList.add(category);
stringList.add(value);
}
br.close();
it works when the variables category and value do not have a comma(,),however the values in the variable value does contain commas.Is there a way that I can split the index of the without using comma?
The solution is given bellow:
BufferedReader br =new BufferedReader(new FileReader("userdetails.txt"));
String str;
ArrayList<String> stringList = new ArrayList<String>();
while ((str=br.readLine())!=null){
int firstIndexOfComma = str.indexOf(',');
String category = str.substring(0, firstIndexOfComma);
String value = str.substring(firstIndexOfComma + 1);
stringList.add(category);
stringList.add(value);
System.out.println(category+" "+value);
}
br.close();
When data has ',' it is generally called CSV file. OpenCSV is fairly used library to handle it. The format looks simple, but it has it quirks. See wikipedia for some details
If I understood you correctly:
String str = "category,vvvv,vvv";
int i = str.indexOf(',');
String category = str.substring(0, i);
String value = str.substring(i + 1);
split() uses regex.
if the reader code works perfectly, do
str.split("\\,");
Not 100% sure, but couldnt you just do
String datavalue [] = str.split("--");
or something?
sample file:
x,y,z--123--Hello World
output:
"x,y,z",
"123",
"Hello World"