Convert Base64 string to JSON in android - android

I have Base64 Encoded string and want to convert it to JSON object.
Here is encoded String
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQU...
Here is how i am doing.
String json = {"image": encode_string};
try{
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
}catch (Throwable t){
t.printStackTrace();
}
But when i write this line String json = {"image":encode_string};i got compile time error.
Unexpected Token
How to resolve that Thanks in advance.

You could make the JSONObject like a HashMap instead of having it parse a string.
This also removes the need for the try-catch.
JSONObject obj = new JSONObject();
obj.put("image", encode_string);

String json = {"image": encode_string};
The right side of this equation doesn't return string value. Instead what you should do is:
String json = "{" + "\"image\":" + encode_string + "}";

Related

How to retrieve JSONobject response specific value in Android

I want to store a particular value of JSONobject response in one variable.
My JSON response is a string:
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
And from this response I want to retrieve the mobile number.
Can Anyone help?
Your Json is
{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}
Parse it Easily
JSONObject jsonObject= new JSONObject(json_response);
String mobile= jsonObject.optString("mobile");
Use asynchttpclient library. Its easy to use and parse values.
add this line in app gradle,
compile 'com.loopj.android:android-async-http:1.4.9'
Then,
Let, String s = "{"username":"admin","password":"admin","mobile":"xxxxxxxxxx"}";
JSONObject jsonObject = new JSONObject(s);
String username = jsonObject.optString("username");
String mobile = jsonObject.optString("mobile");
String password = jsonObject.optString("password");
You need to do something like the below:
final JSONObject jsonObject = new JSONObject(response);
if (jsonObject.length() > 0) {
String mobile = jsonObject.optString("mobile");
Log.e("TAG", "mobile:"+mobile);
}

How would I get a particular value from a JSON?

I'm trying to get a particular value from a field within a JSON file. This is my first time working with a JSON file so I'm not sure if I'm doing it correctly.
try {
URL url = new URL(API_URL + city +".json");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
This block would get the JSON from a weather website and then return the JSON as a string. This string would then be used below. Unfortunately whenever I run this app in Android Studio and go through the logs the logs constantly say that there was no value in weather.
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String weather = object.getString("weather");
Toast.makeText(MyActivity.this, "There is rain", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
What I'm trying to do is grab information from the weather section
Here is the JSON link I'm trying to parse from. This text box thought there were too many links in the JSON response for me to post it here. I'm trying to figure out what is going on and any help would be greatly appreciated.
You can print out response to see if it is exactly your JSON or not.
Assume you get the JSON String correctly.
JSONObject object = new JSONObject(response);
String weather = object.getString("weather");
However, if the JSON your obtained is exactly your response, the above code do not work because there is not weather String. The root only contain response and current_observation.
If what you what to get is weather under current_observation, you should use the code below.
JSONObject object = new JSONObject(response);
JSONObject current_obs = object.getJSONObject("current_observation");
String weather = current_obs.getString("weather"); // Clear
JSONObject object = (JSONObject) new JsonObject(responseString);
String weather = object.getString("weather");
First you need to get your response in string.
Now,start json parsing as per response.
OR
You can use Gson class as well for json parsing.
Get json value from JSONObject:
{"weather":"sunny"}
code snippet to parse the JSONObject.
JSONObject object = new JsonObject(response);
String weather= object.getString("weather");
Get json value from JSONArray:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
code snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
Hope it'll help you.
I have a sample Weather app done using open weather map api. It has all you asked for.
Code here:
http://opensourceandroid.in/weather_forecast.html

json String in android

I have a problem while creating jsonStringer in android. My problem is I have to post values to server using post method.So for that I have to send an array. { "name":"asdf","age":"42","HaveFiles":["abcfile","bedFile","cefFile"]} .
So how can I create a json array for haveFiles? And I don't know the no of files it may varies. So I am creating a string builder and appending the values to that.
when I print the jsonString the stringbuilder show that instead of " it shows \". But when I print the string builder it looks ["abcFile"] like this. but in jsonStringer it prints ["\""abcFile\""]. How I can resolve this issue?
Use this to create json object and pass the json object
try {
JSONObject jObj = new JSONObject(YourString);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
If you want jsonArray then
jobj.getJSONArray(TAG_NAME);
It is really simple, you can use GSON library to do it.
The usage is something like:
Gson gson = new Gson();
String jsonStr = gson.toJson(yourObj);
YourObjType yourObj2 = gson.fromJson(jsonStr, YourObjType.class);
Regarding to your situation, you can do:
Gson gson = new Gson();
String[] ss = new String[] {"abcFile", "defFile", "ghiFile"};
String jsonStr = gson.toJson(ss);
And the result of jsonStr is:
["abcFile, defFile, ghiFile"]

How to print the msg_content in textview android json here?

{
"status": "ERROR",
"msg_content": "Your old password was entered incorrectly. Please enter it again.",
"code": "400",
"msg_title": "Sorry. Error in processing your request"
}
if (str.startsWith("Bad Request"))
{
textview.setText(" ");
}
How to print inside the textview to display the msg_content using json
You need to parse json using JSON object.
JSONObject obj = new JSONObject(str);
Then find string from JSON object whatever you want.
if (obj.has("msg_content")) {
String value = obj.getString("msg_content");
textview.settext(value);
}
You will need to create a JSONObject and pass it the string as a parameter.
JSONObject obj = new JSONObject(str);
Then to find a key in the JSONObject just call, always check if the JSONObject has that key before trying to retrieve it.
if (obj.has("status"){
String status = obj.getString("status");
}
if (obj.has("msg_content"){
String content = obj.getString("msg_content");
textview.setText(content);
}
JsonReader is implemented in API 11. If you want to use it in GingerBread or below try this
Use following Code for extracting Information from JSON Objects:
try {
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if(key.equals("msg_content"))
textView.setText(jsonObject.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, if u have JSON as String, u can populate an object using following code:
try {
jsonObject = new JSONObject(theJsonString);
} catch (JSONException e1) {
e1.printStackTrace();
}
I'm quite new to JSON but I would create a JsonReader and parse the JSON as per here

Android Escaping special characters while parsing JSON

I am using following piece of code for parsing JSON in my android application.
String result = postHttpResponse(uri, json);
try {
JSONObject jsonResult = new JSONObject(result);
boolean authenticated = jsonResult.getBoolean("Authenticated");
if(authenticated){
user = new User();
JSONObject jsonUser = (JSONObject) jsonResult.get("User");
user.setName(jsonUser.getString("Name"));
user.setUserId(jsonUser.getString("UserId"));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
jsonUser.getString("UserId") returns the value "corp\\ns0017" instead of "corp\ns0017". Actualy it is escaping the character "\" in the string with one more "\". but at the time of parsing i want to remove the extra "\". How can i achieve it?

Categories

Resources