Java - parsing ä ö ü - java

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.

Related

URL not being properly build in android

I am using URI Builder class to build this url
http://image.tmdb.org/t/p/w185//qjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg
Here is my code:
`final String TMDB_results = "results";
final String TMDB_title = "original_title";
final String TMDB_poster = "backdrop_path";
JSONObject moviesJson = new JSONObject(moviesJsonStr);
JSONArray resultArray = moviesJson.getJSONArray(TMDB_results);
String[] resultnameStrs = new String[resultArray.length()];
String[] resultposterStrs = new String[resultArray.length()];
for (int i = 0; i < resultArray.length(); i++) {
String moviename;
String movieposter;
// Get the JSON object in which movie title is there
JSONObject movietitle = resultArray.getJSONObject(i);
moviename = movietitle.get(TMDB_title).toString();
movieposter = movietitle.get(TMDB_poster).toString();
//Poster URL Builder
Uri posterbuiltUri = Uri.parse("http://image.tmdb.org/t/p/w185/").buildUpon()
.appendPath(movieposter).build();
String PosterUrl = posterbuiltUri.toString();
resultposterStrs[i] = PosterUrl;
resultnameStrs[i] = moviename;
}
But the URL being build is
http://image.tmdb.org/t/p/w185/%2Fqjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg
Here is a part of JSON String from which I am retrieving data:
{"page":1,"results":[{"adult":false,"backdrop_path":"/kvXLZqY0Ngl1XSw7EaMQO0C1CCj.jpg","genre_ids":[28,12,878],"id":102899,"original_language":"en","original_title":"Ant-Man","overview":"Armed with the astonishing ability to shrink in scale but increase in strength, con-man Scott Lang must embrace his inner-hero and help his mentor, Dr. Hank Pym, protect the secret behind his spectacular Ant-Man suit from a new generation of towering threats. Against seemingly insurmountable obstacles, Pym and Lang must plan and pull off a heist that will save the world.","release_date":"2015-07-17","poster_path":"/D6e8RJf2qUstnfkTslTXNTUAlT.jpg","popularity":54.222073,"title":"Ant-Man","video":false,"vote_average":6.9,"vote_count":1859},.......
I think the '/' is being encoded to '%2F'. Is there any way to stop that?
Any help regrading this is appreciated.
appendPath is encoding the / character from your image path -- you're likely seeing %2F as the encoded (aka URL safe) alternative. Your quickest bet here is to do a quick removal of that first slash (which will also prevent double slash from the base URL and the image URL path).
Uri posterbuiltUri = Uri.parse("http://image.tmdb.org/t/p/w185/").buildUpon()
.appendPath(movieposter.replace("/","").build();
You have an extra '/' in there, encode this instead:
http://image.tmdb.org/t/p/w185/qjn3fzCAHGfl0CzeUlFbjrsmu4c.jpg

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.

Building a json through Gson

i have here a little project that getting data from a table and return it as json with the use of json, but the json its returning seems to be a string. it has back slash, can someone knows what it causes.
Result result = new Result();
result.responseCode = "00";
result.responseMessage = "Successful";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.serializeNulls().create();
String x = "x";
String name="",address ="",msisdn="",email="";
Details details = new Details();
for(DataRow dr : drw_){
name = dr.get("NAME").toString();
details.name = name;
address = dr.get("ADDRESS").toString();
details.address = address;
msisdn = dr.get("CONTACTNUMBER").toString();
details.msisdn = msisdn;
email = dr.get("EMAIL").toString();
details.email = email;
gson.toJson(details);
result.detailsList.add(gson.toJson(details));
}
System.out.println(gson.toJson(details));
System.out.println(gson.toJson(result));
Sample output:
{"responseMessage":"Successful",
"responseCode":"00",
"detailsList":["{\"name\":\"name1\",
\"address\":\"address st 1\",
\"msisdn\":\"09211231234\",
\"email\":\"email#someweb.com\"}"
,"{
\"name\":\"testname\",
\"address\":\"testadress st 1 CITY\",
\"msisdn\":\"+639171234567\",
\"email\":\"myemail#someweb.com\"}
"]
}
Expected Output:
{"responseMessage":"Successful",
"responseCode":"00",
"detailsList":[{"name":"name1",
"address":"address st 1",
"msisdn":"09211231234",
"email":"email#someweb.com"}
,{
"name":"testname",
"address":"testadress st 1 CITY",
"msisdn":"+639171234567",
"email":"myemail#someweb.com"}
]}
The Slashes are escape because of the " value. This can break a string. For example
String x = "{"name":"name1"}" // Not a valid string
String x = "{\"name\":\"name1\"}" // Valid string
Try it out and the compiler will show you the errors.
You are converting it to gson twice.. So the second parsing escapes the double quotes. Try like this
Result result = new Result();
result.responseCode = "00";
result.responseMessage = "Successful";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.serializeNulls().create();
String x = "x";
String name="",address ="",msisdn="",email="";
Details details = new Details();
for(DataRow dr : drw_){
name = dr.get("NAME").toString();
details.name = name;
address = dr.get("ADDRESS").toString();
details.address = address;
msisdn = dr.get("CONTACTNUMBER").toString();
details.msisdn = msisdn;
email = dr.get("EMAIL").toString();
details.email = email;
result.detailsList.add(details);
}
System.out.println(gson.toJson(details));
System.out.println(gson.toJson(result));
Did you try: result.detailsList.add(details);? You should let JSON serialize everything in one go and not put a JSON String inside another object.
You are building a json where each element of detailList list field is an string containing the string representation of other Json previously generated:
result.detailsList.add(gson.toJson(details));
Your detailsList seems to be a list of strings.
detailsList should be a collection of a class Details objects instead of Strings.
This way, the line above should be changed to:
result.detailsList.add(details);
Otherwise, which is happening to you now, you are encoding strings containing quotes thus, these quotes are being encoding with escape characters.

Iterate String Java and select specific word

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.

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