How to extract info from String in android studio? [duplicate] - android

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to display information retrieved from server using php in an android app,I have retrieved the information in a String with json formatting here is the retrieve code and php code.
PHP code
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
//Getting values
$username = $_POST['username'];
require_once('dbConnect.php');
$sql = "SELECT * FROM `employee` WHERE username='$username'";
$result=mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
echo json_encode($row);
}
Android Retrieve code
#Override
protected String doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
HashMap<String,String> params1= new HashMap<>();
params1.put(Config.KEY_EMP_UN,mUsername);
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Config.URl_RET, params1);
return res;
// TODO: register the new account here.
}
#Override
protected void onPostExecute(final String success) {
Toast.makeText(Main2Activity.this,success,Toast.LENGTH_LONG).show();
final TextView Textview1 = (TextView)findViewById(R.id.textView);
Textview1.setText(success);
}
This retrieves info in format shown in below image
What is want to do is extract Name,Designation,Salary,Password and display them in separate TextView.How can I do that?

Take your server response and parse it like this
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("name")) {
String name=jsonObject.getString("name");
}
if (jsonObject.has("designation")) {
String designation=jsonObject.getString("designation");
}
if (jsonObject.has("salary")) {
int salary=jsonObject.getInt("salary");
}
if(jsonObject.has("password")){
String password=jsonObject.getString("password");
}
}catch (Exception e) {
}

you have to parse the json :
JSONObject jsonObject=new JSONObject(success);
//key value for eg : name,salary etc
// now do whatever you want to do
jsonObject.getString("your key value");

There are lots of possible duplicates to this question, so I recommend closing this question after reading this answer.
What you have in here is a JSON response and in order to parse information in JSON, you have to use a JSON parser. Libraries like Gson, Jackson, Moshi will be able to do this.
If you're using Gson, you have to generate model classes of the response which can be written manually or auto-generated using jsonschema2pojo. Once Gson parses your JSON, you can use your model classes getters to access data.
Links to tutorials
https://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
Youtube video
https://www.youtube.com/watch?v=y96VcLgOJqA

Related

How to convert web URL data to JSON format

I am mobile application developer. I want to try to get web URL data in JSON format. I have try to build image aggregator application.
https://yandex.com/images/search?rpt=imageview&url=https%3A%2F%2Favatars.mds.yandex.net%2Fget-images-cbir%2F1973508%2FEArWpseFrv-9jTLCuEUwTw5291%2Forig&cbir_id=1973508%2FEArWpseFrv-9jTLCuEUwTw5291
I am trying this URL data in JSON format like our REST API response. Is it possible to convert JSON data of this URL.
I have also knowledge of Django framework. If it is not possible from front end using android studio then please share me possibility of Django.
Thank you
Try:
import com.google.gson.JsonObject;
import java.net.URLDecoder;
public JsonObject getJson(String url) {
try {
String queryString = url.split("\\?")[1];
String[] members = queryString.split("&");
JsonObject json = new JsonObject();
for (String member : members) {
String key = URLDecoder.decode(member.split("=")[0], "UTF-8");
String value = URLDecoder.decode(member.split("=")[1], "UTF-8");
json.addProperty(key, value);
}
return json;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Response Code 400 Bad Request when use Json String param in Query tag Retrofit 2 Android

I'm using Retrofit 2 to call API in Android App. I have a API, using POST, which have a String param in Query Tag. I do everything like doc suppose and I test this API successfully in Test Page. I can run another API correctly so the problem is not the way I use Retrofit 2.
Here is my interface:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query("list") String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
Here is my implementation:
ArrayList<String> id = new ArrayList<>();
id.add("4782947293");
JSONArray jsonArray = new JSONArray(id);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("list", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String list = jsonObject.toString();
Log.e(TAG, "list: " + list);
apiInterface.getListFriend(21, list, 1,1,"AHHIGHTJGI").enqueue(new Callback<GetListFriendDataResponse>() {
#Override
public void onResponse(Call<GetListFriendDataResponse> call, Response<GetListFriendDataResponse> response) {
Log.e(TAG, " response code: "+ response.code());
}
#Override
public void onFailure(Call<GetListFriendDataResponse> call, Throwable t) {
}
});
I always get response code: 400 when use this API.
I'm focusing the "list" var. "list" is a JSON text but I wonder if method "jSon.toString()" is right to get a String from a JSONObject, which can using in Retrofit 2. List param form is:{"list":["12332"]} .
Please help me!
Questions
1) Why you are creating JSONObject and JSONArray on your own?
2) You are creating string using whatever you are creating json.
Eg: {list:["123","456"]}
you are trying pass whole json, I think, instead you need to pass just the array of string to the list key.
Request Sending
{
list:["123","456"]
}
suppose the above json is the request you want to send to server
Now, create model class goto http://jsonschema2pojo.org and paste your json and select json and gson at right side and click on preview.
It will show the classes to map you json to model. Use this model class to set the list to the key in your json
I found my problem. The JSON text contains some special character so I need to convert them to URL encode.
Correct request URL like this:
http://54.169.215.161:8080/users/29/add_friend?list=%7B%22list%22%3A%5B%2215536%22%5D%7D&platform=google
By using Retrofit 2, it uses the URL:
http://54.169.215.161:8080/users/29/add_friend?list={%22list%22:[%2215536%22]}&platform=google
So I get Bad Request Response code.
Retrofit 2 also provides method to convert char sequence to URL encode but it 's not enough. So I don't use Retrofit 's convert method by using this code: encode= true.
so my interface is:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query(value = "list",encoded = true) String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
And I manually convert JSON text to URL encode by code:
list = list.replace("{", "%7B");
list=list.replace("]", "%5D");
list=list.replace("[", "%5B");
list=list.replace(":", "%3A");
list=list.replace("}","%7D");
list = list.replace("\"", "%22");
That's all. Now I can get data by using API.
Suggestion: If u have the same problem, check the URL retrofit return in response and compare to correct URL to see special character, which is not converted to URL encode.

Convert Twitter4j Status to JSON Object

Android 2.3.3
I am integrating Twitter API into my android application. I am using Twitter4j.
I could get the tweets for a particular user, using the below code.
Paging paging = new Paging(1, 40);
List<twitter4j.Status> statuses = twitter.getUserTimeline("xxx", paging);
Log.d(Const.TAG,"Showing Timeline.");
for (twitter4j.Status status : statuses) {
String rawJSON = DataObjectFactory.getRawJSON(status);
}
My requirement is that I need to parse the JSON String (rawJSON), to get some other values like, published date and so on.
I am pretty new to JSON parsing esp., with converting things to JSON. All i know in the above code is that, String rawJSON = DataObjectFactory.getRawJSON(status); converts the Status Object to a String and I can view it by logging it.
How do I convert this String to a JSONObject or a JSONArray? Can someone provide me with a sample code?
I tried the below code, but it gives an exception
try {
JSONObject tweet = new JSONObject(rawJSON);
JSONArray textArray = tweet.getJSONArray("text");
String text = textArray.getString(0);
Log.d(Const.TAG, "Text = "+text);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d(Const.TAG, "Error while converting string to json");
e.printStackTrace();
}
Here's my code to parse a Twitter4j Status. This example get the language of the tweet.
//Status To JSON String
String statusJson = DataObjectFactory.getRawJSON(status);
//JSON String to JSONObject
JSONObject JSON_complete = new JSONObject(statusJson);
//We get another JSONObject
JSONObject JSON_user = JSON_complete.getJSONObject("user");
//We get a field in the second JSONObject
String languageTweet = JSON_user.getString("lang");
I got a way to get values from Status object without the need to convert it into JSON. Of course this is very basic, by I overlooked it.People who have trouble getting values from Status object, can look at this.
You can get all the values by using the object of Status.
For example, if "status" is an object of Status, we can get the text of the tweet, by using, status.getText() and the user value by using status.user() and so on. Just work on the status object a bit and you will find all the values you need.

how to parse complicated json in android

I have been following a tutorial and finally have understand to a decent degree using AsyncTask and how to send an http get request to get the json returned. I can get the json, I think successfully but am having trouble parsing it.
The tutorial I was looking at uses a pretty simple weather api which sends back pretty easy json to parse.
Mine is a search result with info on each item. My json looks like this:
http://pastebin.com/f65hNx0z
I realize the difference between json objects and the arrays of info. Just a bit confused on how to parse over to get information on each beer and the brewery info.
My code below:
String jsonUrl = url + query;
Toast.makeText(this, jsonUrl, Toast.LENGTH_SHORT).show();
//todo: get json
new ReadJSONResult().execute(jsonUrl);
return false;
}
private class ReadJSONResult extends AsyncTask
<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
///code below is what I kow I need to reconstruct and change to parse
JSONObject jsonObject = new JSONObject(result);
JSONObject weatherObservationItems =
new JSONObject(jsonObject.getString("weatherObservation"));
Toast.makeText(getBaseContext(),
weatherObservationItems.getString("clouds") +
" - " + weatherObservationItems.getString("stationName"),
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
}
}
You should use a JSON deserializer library to object which supports nested objects, also. I recommend Gson https://code.google.com/p/google-gson/
There is a Java class generator from JSON response. jsongen.byingtondesign.com will parse your json response and give you Java Bean class. which will help you to understand the need.

Parsing JSON String obtained frm server in Android

I had gone through a link on parsing Json data on Android, but didnt understand pretty much.
I am getting the following JSON String from my server.
I need to parse it and present it as a listview in my android app. ANy guidance or code snippet.?
Also since my Jason string has data for images, will the listview be able to display it properly?
My JSON String is:
{"results":{"result":[{"year":"2012","title":"The Amazing Spider-Man","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Marc Webb","rating":"7.3","cover":"http:\/\/i.media-imdb.com\/images\/SF1f0a42ee1aa08d477a576fbbf7562eed\/realm\/feature.gif"},
{"year":"2014","title":"The Amazing Spider-Man 2","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Marc Webb","rating":"7.3","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BMzk3MTE5MDU5NV5BMl5BanBnXkFtZTYwMjY3NTY3._V1._SX54_CR0,0,54,74_.jpg"},
{"year":"2002","title":"Spider-Man","details":"http:\/\/www.imdb.com\/title\/tt0948470","director":"Sam Raimi","rating":"6.3","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BODUwMDc5Mzc5M15BMl5BanBnXkFtZTcwNDgzOTY0MQ##._V1._SX54_CR0,0,54,74_.jpg"},
{"year":"2007","title":"Spider-Man 3","details":"http:\/\/www.imdb.com\/title\/tt1872181","director":"Sam Raimi","rating":"7.5","cover":"http:\/\/ia.media-imdb.com\/images\/M\/MV5BMjE1ODcyODYxMl5BMl5BanBnXkFtZTcwNjA1NDE3MQ##._V1._SX54_CR0,0,54,74_.jpg"},
{"year":"2004","title":"Spider-Man 2","details":"http:\/\/www.imdb.com\/title\/tt1872181","director":"Sam Raimi","rating":"6.8","cover":"http:\/\/i.media-imdb.com\/images\/SFa26455c07afc3c94f52e95de50d5d814\/realm\/tv_series.gif"}]}}
Make Arraylist of All Fields and Write below function to parse above json, it will solve your problem.
ArrayList<String> year, title, details, director, rating, cover;
// For Parse Login Response From Server
public void mParseResponse() throws UnknownHostException {
year=new ArrayList<String>();
title=new ArrayList<String>();
details=new ArrayList<String>();
director=new ArrayList<String>();
rating=new ArrayList<String>();
cover=new ArrayList<String>();
try {
JSONObject jObject = new JSONObject(EntityUtils.toString(entity));
JSONObject jsonobjresults = jObject.getJSONObject("results");
JSONArray jsonarrayresult = jsonobjresults.getJSONArray("result");
for(int i=0;i<jsonarrayresult.length(); i++){
JSONObject mJsonObj = jsonarrayresult.getJSONObject(i);
year.add(mJsonObj.getString("year"));
title.add(mJsonObj.getString("title"));
details.add(mJsonObj.getString("details"));
director.add(mJsonObj.getString("director"));
rating.add(mJsonObj.getString("rating"));
cover.add(mJsonObj.getString("cover"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
read this tutorial http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html.
You can use gson library of Google to parse json.
you need to create java classes to store json values
passs that class ref to gson libary. It has simple methods.
chec this doc

Categories

Resources