Iterate String Java and select specific word - java

I have the following String:
[{"index":1,"image":"1234a.jpg","thumbnail":"1234a_t.jpg","medium":"1234a.jpg"},
{"index":2,"image":"43215256b.png","thumbnail":"43215256b_t.jpg","medium":"43215256b.jpg"}]
I would like to select only JPG name or the pngs like (1234a.jpg OR 43215256b.png) and ignore the rest of the String, How can I do that in Java?? I tried substring but it works not fine because the names of the JPGs are different.
Here a piece of my Java code:
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("imageID", c.getString("imageID"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
Where image is a database field that contains the String above, So I would like to select the JPGs names OR the PNGs names from the content of c.getString("image") I tried JSON but not worked, mabye have someone better Idea?? please help.

You should use a regular JSON parser. If this is not possible use the regex (?<=")\w+\.jpg(?=") to find the names enclosed in quotes ("") ending with jpg.
When using a Java Pattern, you need double \ inside the String "(?<=\")\\w+\\.jpg(?=\")"

Try this:
Modified Your Code:
for (int i = 0; i < data.length(); i++)
{
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
if(isValid(c.getString("image")))
{
map.put("imageID", c.getString("imageID"));
map.put("image", c.getString("image"));
MyArrList.add(map);
}
}
This is my Patch:
public boolean isValid(String value)
{
String jpgChk = "\\.jpg$";
String pngChk = "\\.png$";
Matcher jpgMatcher = Pattern.compile(jpgChk).matcher(value);
Matcher pngMatcher = Pattern.compile(pngChk).matcher(value);
if(jpgMatcher.find())
return value.contains(".png")?false:true;
else if (pngMatcher.find())
return value.contains(".jpg")?false:true;
else
return false;
}
This is long but immediate solution to your problem. If works accept it or we will try to minimize and optimize this one

Parse it in json format and check for each key if the value has a substring of jpg. if yes then you can use the whole value.

Related

String to map conversion java

Code:
Map test = new HashMap<String,String>();
test.put("1", "erica");
test.put("2", "frog");
System.out.println(test.toString());
This code gives output as :
{1=erica, 2=frog}
I want this output to be again put in a map as key value-pair .
Any suggestions how can i implement this ?
Or is ther any predefined utility class for conversion of the output to HashMap again ?
For me a proper way would be to use a JSON parser like Jackson since the way a HashMap is serialized is not meant to be parsed after such that if you use specific characters like = or , they won't be escaped which makes it unparsable.
How to serialize a Map with Jackson?
ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(myMap);
How to deserialize a String to get a Map with Jackson?
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(contentToParse, Map.class);
You can try to use this:
String[] tk = mystring.split(" |=");
Map<String, String> map = new HashMap<>();
for (int i=0; i < tk.length-1; i++)
{
map.put(tk[i], tk[i]);
}
return map;
If you want to replicate the Java code filling the map, you may use something like this:
StringBuilder sb = new StringBuilder("Map<String, String> test = new HashMap<>();");
for(Map.Entry<?, ?> entry : test.entrySet())
{
sb.append("\ntest.put(\"");
sb.append(entry.getKey());
sb.append("\", \"");
sb.append(entry.getValue());
sb.append("\");");
}
String string = sb.toString();
System.out.println(string);
But I agree with the comments, that in many applications a format such as JSON is more appropriate to serialize a map.
Note that the above solution does not escape strings, it only works if the strings don't contain characters like " or \n. If you need to handle these cases it will become more complicated.
You could try the following:
String out = test.toString();
Map<String, String> newMap = new HashMap();
// remove the first and last "{", "}"
out = out.subString(1,out.size()-1)
String[] newOut = out.split(", ");
for (int i=0; i<newOut.length;i++){
// keyValue is size of 2. cell 0 is key, cell 1 is value
String[] keyValue = newOut.split("=");
newMap.put(keyValue[0], keyValue[1]);
}
I haven't tested the code in java i just wrote from my mind. I hope it will work

Java: Gson change property name without serialization

Is it possible to change the name of a Json property without serialization with Gson? For example, given this Json
{
"1": {
...
},
"2": {
...
}
}
could I change the "1" to a "3" without removing its contents. I know that the addProperty method adds a new property, or overwrites an existing property with a new value, but I want to change the name of a property without affecting its value. Also, pasting the existing value as the second argument of addProperty will not suffice.
EDIT: To add more context, I will explain the bigger picture. I have a JSON string that is a couple thousand lines long. I'm writing a program leveraging Gson in order to change the values in that JSON string. I am at a point where I not only want to change the values of properties, but the names of the properties themselves. I have done everything so far without serialization.
Here is a snippet of the Java I wrote:
String file = "\\temp.json";
FileReader reader = new FileReader(file);
JsonStreamParser parser = new JsonStreamParser(reader);
// Parse entire JSON
JsonElement element = parser.next();
// Get root element
JsonObject sites = element.getAsJsonObject();
// Get first child element
JsonObject site1 = sites.getAsJsonObject("1");
JsonObject clust1 = site1.getAsJsonObject("CLUST");
for(int i = 1; i < 12; i++) {
// "Dynamic" variable
String num = Integer.toString(i);
// Get property whose name is a number, has siblings
JsonObject one = custCluster1.getAsJsonObject(num);
one.getAsJsonObject().addProperty("name", "cluster" + i);
JsonObject subOne = one.getAsJsonObject("SUB");
subOne.getAsJsonObject().addProperty("name", "aName" + i);
for(int n = 1; n < 1002; n++) {
// "Dynamic" variable
String inst = Integer.toString(n);
// Get property whose name is a number, has siblings
JsonObject subSub = subOne.getAsJsonObject(inst);
// If the property doesn't exist, then don't execute
if(subSub != null) {
JsonArray subSubArray = subSub.getAsJsonArray("SUBSUB");
subSub.getAsJsonObject().remove("name");
int m = 0;
while(m < subSubArray.size()) {
subSubArray.get(m).getAsJsonObject().remove("SR");
subSubArray.get(m).getAsJsonObject().remove("FI");
subSubArray.get(m).getAsJsonObject().remove("IND");
subSubArray.get(m).getAsJsonObject().addProperty("ST", "1");
subSubArray.get(m).getAsJsonObject().addProperty("ID", "2");
subSubArray.get(m).getAsJsonObject().addProperty("DESCR", "hi");
m++;
}
m = 0;
}
}
}
Thanks to #mmcrae for helping and suggesting this method.
Since I'm already saving the (key, value) pairs in variables, you can remove the property whose name you want to change from the parent, and then add it back with a new name and the content that was already saved.
Like this:
JsonObject sites = element.getAsJsonObject();
JsonObject site1 = sites.getAsJsonObject("1");
JsonObject clust1 = site1.getAsJsonObject("CLUST");
site1.remove("CLUST");
site1.add("NEWCLUST", clust1);

how to parse arrays with direct values, twice json encoded

How can i parse an array with direct values , twice json encoded in Java, i get the data as a string and i want to get each value from the multidimensional array.
I'm kind of a noob regarding java, i managed to pull a not so elegant solution that encounters problems when i split by "," if the text inside has "," i could do it with regex but there must be a more elegant solution than this:
content = the data fetched from the api as a string
content = content.replace("\"[[", "[");
content = content.replace("]]\"", "]");
content = content.replaceAll("\\\\","");
for (String FaData : content.split("\\],\\[")) {
for (String FaDataData : FaData.split(",")) {
FaDataData.toString();
}
}
Here you have an example of how content string actually looks like when is fetched:
"[[308576,1410880665,162506,\"Bobcat\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308576.jpg\",\"Well no\",82,3,\"\"],[308592,1410883832,9479,\"undeathkiller\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308592.gif\",\"Guess the stupidity level\",89,9,\"\"],[308574,1410879991,32277,\"rady123lol\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308574.gif\",\"force of habit\",92,3,\"\"],[308624,1410897686,149704,\"Raptide7\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308624.jpg\",\"*breathing intensifies*\",114,8,\"\"],[308648,1410911037,114669,\"Huller\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308648.jpg\",\"SPOILERS: Stannis kills Dumbledore\",133,2,\"\"],[308628,1410898654,135315,\"Mig_L\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308628.jpg\",\"So badass\",117,2,\"gold\"],[308639,1410902872,62886,\"burningowl\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308639.jpg\",\"Kid's going places yo\",125,4,\"\"],[308520,1410858123,73400,\"koppie888\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308520.jpg\",\"4chan, what a beautifull place\",99,7,\"\"],[308546,1410872801,32277,\"rady123lol\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308546.jpg\",\"( \\u0361\\u00b0 \\u035c\\u0296 \\u0361\\u00b0)\",118,17,\"\"],[308486,1410846601,176339,\"AtLeastISubmit\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308486.jpg\",\"That 70's show called it.\",101,3,\"\"]]"
Assuming that you have your text in a String variable called everything, using the JSONSimple package, you can use the following code:
try {
// create a new JSONParser
JSONParser parser=new JSONParser();
// first JSON decoding
Object obj = parser.parse(everything);
// second JSON decoding
obj = parser.parse(obj.toString());
// cast the parsed JSON string to a new JSONArray
JSONArray array = (JSONArray)obj;
// loop through each line of the initial JSONArray
for (int i = 0; i < array.size(); i++){
// write the array values as a single line
System.out.println(i + " : " + array.get(i));
// parsing each line as a new JSONArray
JSONArray tmp = (JSONArray)parser.parse(array.get(i).toString());
for (int j = 0; j < tmp.size(); j++){ // iterate over the parsed values
System.out.println(i+"."+j+" : "+tmp.get(j));
}
}
} catch (ParseException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
Of course, you also have to import the following classes from the JSON package :
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
Try this
content = content.trim();
content = content.substring(0, content.length()); //gets the length of content string
content = content.replaceAll("\\/","/"); //Replaces all \/ to /
It would apply to the brackets as well.
If you're using JSON then I would suggest using a JSON library such as jackson.
ObjectMapper mapper = new ObjectMapper();
String[][] 2Darray = mapper.readValue(content, String[][].class);
But then, if you are using JSON it would be nice if the format of your data was more structured. Obviously, that depends on whether or not you have any control over the API.

Java - parsing ä ö ü

Sorry for my bad English, i'm from Germany, but i hope, i'm understandable.
String = Dömä
Result = D(any signs)m(any signs)
My Code:
JSONObject json = jsonParser.makeHttpRequest(UserFactory.GET_URL, "POST", paramsx);
sList = new ArrayList<Data>();
JSONArray cast = json.getJSONArray("friends");
for (int i = 0; i < cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String fullname = actor.getString("fullname");
String country = actor.getString("country");
String profile_image = actor.getString("profile_image");
sList.add(new Data(fullname, country, profile_image));
}
How can I fix this problem?
There are problems with your character encoding. You need to make sure the character encoding you are using for the JSON supports the language you are using and that both ends of the link are using the same encoding.

What should I do to solve this error?

I was using JSONParser to obtain results of a search, for that I followed this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
The thing is that, the API I am using gives the results like this:
{"response":[50036,{"aid":88131498,"owner_id":61775052,"artist":"Terror Squad","title":"Lean Back (OST Need For Speed Underground 2)","duration":249,"url":"http:\/\/cs4408.vkontakte.ru\/u59557424\/audio\/7f70f58bb9b8.mp3","lyrics_id":"3620730"},{"aid":106963458,"owner_id":-24764574,"artist":"«Dr. Dre ft Eminem, Skylar Grey (Assault Terror)","title":"I Need A Doctor (ASSAULT TERROR DUBSTEP REMIX)»","duration":240,"url":"http:\/\/cs5101.vkontakte.ru\/u79237547\/audio\/12cd12c7f8c2.mp3","lyrics_id":"10876670"}]}
My problem comes when I have to parse the first integer (here it is 50036) which is the number of results found.
I don't know how to read that integer.
This is my code:
private void instance(String artisttrack){
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String jsonurl = new String( "https://api.vk.com/method/audio.search?access_token=ACC_TOKEN&api_id=ID&sig=SIG&v=2.0&q=" + artistname + artisttrack + "&count=5");
JSONObject json = jParser.getJSONFromUrl(jsonurl);
try {
// Getting Array of Contacts
response = json.getJSONArray(TAG_RESPONSE);
// looping through All Contacts
for(int i = 0; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
// Storing each json item in variable
//int results = Integer.parseInt(c.getString(TAG_RESULTS));
String aid = c.getString(TAG_AID);
String owner_id = c.getString(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
String duration = c.getString(TAG_DURATION);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
String url = c.getString(TAG_URL);
String lyrics_id = c.getString(TAG_LYRICS_ID);
Log.e("áaaaaaaaaaaaaaa", url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The JSONParser.java is like written in the tutorial.
And here 2 lines of the logcat error:
W/System.err(10350): org.json.JSONException: Value 50036 at 0 of type java.lang.Integer cannot be converted to JSONObject
W/System.err(10350): at org.json.JSON.typeMismatch(JSON.java:100)
Your JSON sample is a poor way to organize the results: mixing the number in with the result objects. Is the number supposed to indicate the number of objects in the array or something else?
If you can assume that this number will always be the first element, and according to this then it's supposed to work this way, you can try to read the first value of the array outside the loop:
response = json.getJSONArray(TAG_RESPONSE);
// from your example, num will be 50036:
num = response.getInt(0);
for (int i = 1; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
Note that the example in the linked documentation has this number as a string:
{"response":
["5",
{"aid":"60830458","owner_id":"6492","artist":"Noname","title":"Bosco",
"duration":"195","url":"http:\/\/cs40.vkontakte.ru\/u06492\/audio\/2ce49d2b88.mp3"},
{"aid":"59317035","owner_id":"6492","artist":"Mestre Barrao","title":"Sinhazinha",
"duration":"234","url":"http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"}]}
But JSONArray.getInt() will parse the String as an int for you.
And notice that some of the values in the objects in your array are also numbers, you may want to read those as int also:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
int duration = c.getInt(TAG_DURATION);
A lot of the values you are trying to parse in are not String objects, specifically "aid", "owner_id", and "duration". Use the correct method to retrieve values. For example:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
int duration = c.getInt(TAG_DURATION);
edit: Another error that I missed is you start your array with 50036. This is not a JSONObject and cannot be parsed as so. You can add a conditional statement to check if it's array index 0 to parse the int using getInt(), and then parse as JSONObjects for the rest of the array values.
Try changing
response = json.getJSONArray(TAG_RESPONSE);
into
response = (JSONObject)json.getJSONArray(TAG_RESPONSE);
I dont have any experience with JSONObject, but works often with type mismatches.
Try putting 50036 in quotes like this "50036" .

Categories