String.split for JSON array - java

I have the following string and I need to split it to get the two objects inside:
[Object{value1="1", value2="2"}, Object{Value1="1", value2="2"}]

You could try:
String[] splitTextObject = YOUR_STRING.split(", ");
String object1 = splitTextObject[0];
String object2 = splitTextObject[1];
...
But I don't think you actually need to split the string this way in order to achieve getting each object, and instead you should consider parsing your JSON. Perhaps utilise GSON.

Related

How to extract data from Json array?

Using Jsonobject I extracted data from RawmatrixData and stored it in Object:
org.json.JSONObject item = Fir.getJSONObject(i); Object value1 = item.get("RawMatrixData")`
Now i want to replace data 342771123181 with some string value, how to achieve this?
I tried with ArrayList<String> and ArrayList<ArrayList<String>>.
"LstMatrixFirmInfo": [
{
"RawMatrixData": "[[342771123181,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[3427714486446,1,2,null,null,null,null,null,null,null,null,null,null,null,28.99,28.99,28.99,25,4.81,4.81,4.81,null,null,null,null,null,null,null,null,null]]]}
Is RawMatrixData supposed be a string like in the image or JSON Array.
If RawMatrixData is supposed to be string then maybe converted to JSONArray
I would just use string replace.
String replacedText = Fir.getString('RawMatrixData').replace('342771123181', 'foobar')
Fir.push('RawMatrixData', replacedText);
The above can be done in one line but for ease of understanding it hasn't. First line gets your string from the Json object then replace the number with foobar.
Then text is pushed back on to the json object overwriting the old value.
The above code i believe sorts out your problem based on the picture you provided.
If the RawMatrixData was supposed to be a JSON array and not a string then in that case you would have to traverse the whole array replace as you go.

Get string from ("\n") new line operator

I have an arraylist that containing string like abc"\n"1234,cde"\n"567 fgh"\n"890. I want to get string from where it found new line. like from this array i want only 1234,567 and 890. here is what am doing. but it says "Incompatible Types"
Thanks actually i have show the dialog that containing these contacts.and than if user click on any contacts it opens the dialer activity.
for(String contact: manycontacts){
String contacts=contact.split("\\r?\\n");
}
split returns a String[] not a String
for(String contact: manycontacts){
String[] contacts=contact.split("\\r?\\n");
}
If you need it as one string you have to iterate over the array and concatinate the strings. or use commons-utils from apache to join it.
split method returns an array of strings String[]. In your code, you're returning a simply String. That is the incompatibility.
Simple change it to:
for(String contact: manycontacts){
String[] contacts=contact.split("\\r?\\n");
}
The split function returns an array of Strings, but you are trying to assign an array of strings to a single string, which throws this error. Rather use:
for(String contact: manycontacts){
String[] contacts=contact.split("\\r?\\n");
for(String split : contacts) {
//here you can go on and workt with a single splittet value
}
}
contact.split() is returning a String array, not a String, hence the type is incompatible. You'll need
String[] contacts = contact.split("\\r?\\n");
It is because split returns array of String which will be String[].
simply i used this.to trim the string.
String numberonly = contacts.substring(contact.indexOf('\n'));

Converting ArrayList to String to store in Shared Preferences

i have ArrayList with multiple value. i want to convert this ArrayList into String to save in sharedPreferences, then I want to retrieve the String and convert it back to ArrayList
Please tell how to do that? (or any other idea to store and retrieve ArrayList)
Convert arraylist to string:
String str = "";
for (String s : arraylist)
{
str += s + ",";
}
Save string into sharedpreference:
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("mystr", str).commit();
get string from sharedpreference:
String str = PreferenceManager.getDefaultSharedPreferences(context).getString("mystr", "defaultStringIfNothingFound");
Convert string to arraylist:
List<String> arraylist = new ArrayList<String>(Arrays.asList(str.split(",")));
You can use Google's GSON.
Gson is a Java library that can be used to convert Java Objects into
their JSON representation. It can also be used to convert a JSON
string to an equivalent Java object. Gson can work with arbitrary Java
objects including pre-existing objects that you do not have
source-code of.
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html
https://code.google.com/p/google-gson/
You get the idea:
Store: Convert Object to JSON String -> Save string
Retrieve: Get string -> Convert from JSON to Object

How to get rid of duplicate entries in a comma separated string in java?

I have a string places="city,city,town". I need to get "city,town". Basically get rid of duplicate entries in the comma separated string.
places.split(","); will give me array of String. I wonder, if I can pass this array to a HashSet or something, which will automatically get rid of duplicates, but trying something like:
HashSet test=new HashSet(a.split(","));
gives the error:
cannot find symbol
symbol : constructor HashSet(java.lang.String[])
Any neat way of achieving this, preferably with least amount of code?
HashSet<String> test=new HashSet<String>(Arrays.asList(s.split(",")));
this is because HashSet does not have a constructor that expects an array. It expects a collection, which is what I am doing here by Arrays.asList(s.split(","))
String s[] = places.split(",");
HashSet<String> hs = new HashSet<String>();
for(String place:s)
hs.add(place);
If you care about the ordering I'd suggest you use a LinkedHashSet.
LinkedHashSet test = new LinkedHashSet(Arrays.asList(a.split(",")));
Another way of doing this in Java 8 would be:
Lets say you have a string str which is having some comma separated values in it. You can convert it into stream and remove duplicates and join back into comma separated values as given below:
String str = "1,2,4,5,3,7,5,3,3,8";
str = String.join(",",Arrays.asList(str.split(",")).stream().distinct().collect(Collectors.toList()));
This will give you a String str without any duplicate
String[] functions= commaSeperatedString.split(",");
List<String> uniqueFunctions = new ArrayList<>();
for (String function : functions) {
if ( !uniqueFunctions.contains(function.trim())) {
uniqueFunctions.add(function.trim());
}
}
return String.join(",",uniqueFunctions);
or you can use linkedHashset
LinkedHashSet result = new LinkedHashSet(Arrays.asList(functions.split(",")));

Referring a variable with a variable in java

I have got into a strange strange situation. I have 3 sets of strings like this
String set1q1="something"; //associated with randomNum=1
String set1q2="something";
String set1q3="something";
String set1q4="something";
... and so on
String set2q1="something"; //randomNum=2
String set2q2="something";
String set2q3="something";
String set2q4="something";
... and so on
String set3q1="something"; //randomNum=3
String set3q2="something";
String set3q3="something";
String set3q4="something";
... and so on
All these strings are initialised only once. Now in my program i generate a random number between 1-3. I converted this random number into a string and stored it into a string called set.
String set=randomNum.toString();
Now next intead of using "if-else" to send the data(if randomnum=1 send set1q1-5, if randomnum=2 then send set2q1-5), I want the appropriate data to be sent using one line.
For example: if random no 2 is chosen then set2q1 has to be sent where the "2" in between is has to be the value of "set"(which is defined above).
set"set"q1 //where set can be 1,2,3
Is there any way to do this?
What you are asking for is not possible;1 it's just not the way Java works. Why don't you just use an array, or a collection?
List<List<String>> allTheStrings = new ArrayList<List<String>>();
List<String> myStrings = null;
// Add a subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
// Add another subset
myStrings = new ArrayList<String>();
myStrings.add("something");
myStrings.add("something");
myStrings.add("something");
allTheStrings.add(myStrings);
...
// Obtain one of the strings
String str = allTheStrings.get(1).get(2);
1. Except in the case where these variables are members of a class, in which case you could use reflection. But really, don't.
It is not possible. Local variable identifiers are converted to numbers (stack offsets) during compilation. But you should use arrays or collections anyway
Sounds like you want to index Strings by two indices. You should use a two-dimensional String array: String[][] strings. You may then access the desired string with strings[n][m]
Or you can achieve the same effect with a List<List<String>> strings if you need the dimensions of your 2D array to grow dynamically. You'd access the value you need with strings.get(n).get(m)
If you really want to access your strings by a composed name such as set2q1, then you just need a Map<String, String> strings. Then you'd access each value with strings.get("set" + m + "q" + n)
looks to me you should look into arrays, like this:
String[] strings = new String[]{"xxx", "yyy", "zzz"};
String string = strings[randomNumber];
create an arraylist instead and reference using the list index

Categories

Resources