How can I separate string? - android

When I'm printing String, in logcat I'm getting like this:
{"urldetails":"aHR0cDydmljZXMvfmh0dHA6Ly80Ny45MS4xMTUuMjEyL1NDTVMvd2ViL2FwcF9zYm94LnBocA==","customer":"NH4fjIyOTF+RHIuQWZhcmdoZXNl"}
In this 3 things I want store in separately, one is urldetails, one iscustomer before + and 3rd one is after + String.
How can I do that?
When I tried, I'm getting indexoutofbounf exception

You can extract the values with JSONObject.
JSONObject json = new JSONObject(your-string);
String urldetails = json.getString("urldetails");
String[] customers = json.getString("customer").split("\\+");
String customer1 = customers[0]; //customer before +
String customer2 = customers[1]; //customer after +

try use kotlin
yourModel = Gson().fromJson(this, T::class.java)
yourModel.customer.substringAfter("+")
yourModel.customer.substringBefore("+")

Related

How to get parameters values from a URL

I have an issue in getting parameters from a URL mentioned below,
String url = http://example.com/api_callback#access_token=XXXXXXXXXXXXXXX&state=enabled&scope=profile%20booking&token_type=bearer&expires_in=15551999
My code to extract the parameters is as follows:
Uri uri = Uri.parseurl(url);
Set<String> paramNames = uri.getQueryParameterNames();
However, as you can see a "#" in the URL instead of "?" so that's why I am not able to get the parameters Set.
First thing that came to my mind is to replace "#" with "?" using String.replace method then I thought their might be better solution for this. So if you guys have better solution please help me.
Easiest method:
String string = url.replace("#","?");
String access_token = Uri.parse(string).getQueryParameter("access_token");
Log.d("TAG", "AccessToken: " + access_token);
Now you can get any parameter from the url just by passing their name.
Good Luck
'#' is called refrence parameter, Here you can do one of two things either replace the '#' with '?' and process your uri i.e
String url = "http://example.com/api_callback#access_token=XXXXXXXXXXXXXXX&state=enabled&scope=profile%20booking&token_type=bearer&expires_in=15551999";
url = url.Replace("#","?"); //now your URI object to proceed further
or other alternative
String url = "http://example.com/api_callback#access_token=XXXXXXXXXXXXXXX&state=enabled&scope=profile%20booking&token_type=bearer&expires_in=15551999";
URL myurl = new URL(url);
String refrence = myurl.getRef(); //returns whatever after '#'
String[][] params = GetParameters(refrence);
and the defination for function GetParameters() is following
private String[][] GetParameters(String r)
{
try
{
String[] p = r.split("&"); //separate parameters mixed with values
String[][] data = new String[p.length][2];
for(int i = 0 ; i<p.length; i++) //iterate whole array
{
data[i][0] = p[i].split("=")[0]; //parameter name
data[i][1] = p[i].split("=")[1]; //parameter value
data[i][1] = data[i][1].replace("%"," "); //replace % with space character
}
return data; //return result
}
catch(Exception e)
{
return null;
}
}
i have not executed and tested the code i am lazy one too so i hope you will accomodate lolz :D
You can use the Uri class in Android to do this; https://developer.android.com/reference/android/net/Uri.html
Uri uri = Uri.parse("http://www.chalklit.in/post.html?chapter=V-Maths-Addition%20&%20Subtraction&post=394");
//Then you can even get a specific element from the query parameters as such;
String chapter = uri.getQueryParameter("chapter"); //will return "V-Maths-Addition "
Uri uri = Uri.parse("http://www.chalklit.in/post.html?chapter=V-Maths- Addition%20&%20Subtraction&post=394");
String server = uri.getAuthority();
String path = uri.getPath();
String protocol = uri.getScheme();
Set<String> args = uri.getQueryParameterNames();
Then you can even get a specific element from the query parameters as such;
String chapter = uri.getQueryParameter("key");

android - parsing JSONArray that doesn't have explicit JSONObject

I know how to parse JSON that looks like [{...},{...},{...}]. But here is my example and something is a bit different:
[{"type":"sometype","presentations":["/files/presentation/presentation.pdf"],"description":"somedescription"},{"type":"sometype","presentations":["/files/presentation/presentation2.pdf"],"description":"somedescription"}]
How to parse data from "presentations" here? I'm getting it as JSONArray, but can't get a value (using .toString() with that array returns that value, but with "\" before "/" (I mean "/files/presentation..."), so I can't add it to url to display pdf. And I don't know how to get JSONObject from that array (if it exists, of course).
String jsonString = "[{\"type\":\"sometype\",\"presentations\":[\"/files/presentation/presentation.pdf\"],\"description\":\"somedescription\"},{\"type\":\"sometype\",\"presentations\":[\"/files/presentation/presentation2.pdf\"],\"description\":\"somedescription\"}]";
try {
JSONArray jaArray = new JSONArray(jsonString);
JSONObject firstElement = jaArray.getJSONObject(0);
JSONArray jaPresentations = firstElement.getJSONArray("presentations");
String string = jaPresentations.getString(0);
//or chain it together like so:
String string2 = jaArray.getJSONObject(1).getJSONArray("presentations").getString(0);
Log.v("TAG", string);
Log.v("TAG", string2);
Output:
V/TAG﹕ /files/presentation/presentation.pdf
V/TAG﹕ /files/presentation/presentation2.pdf

Android JSON multiple pairs parse

I have a JSONObject like this
{"message":{"context":"ws","data":"","id":"12345","http_accept":"json","method":"GET","search_key":"cat"},"response":{"1":"cat", "2":"catte"},"status":"OK","code":200}.
I am trying to get the result of a search webservice. I want the value of the pairs from the "response" key to add them to an ArrayList.
For example, from this "response" I want "cat" and "catte". How can I parse to get them?
Use a JSON Iterator to loop over all the keys and collect the response values.
JSONObject root = new JSONObject(jsonInput);
JSONObject resp = root.getJSONObject("response");
List<String> respList = new ArrayList<String>();
for (Iterator<String> iterator = resp.keys(); iterator.hasNext();) {
String key = iterator.next();
respList.add(resp.getString(key));
System.out.println(key + " = " + resp.getString(key));
}
System.out.println(respList);
Output :
1 = cat 2 = catte [cat, catte]
"response"s structure is map. You can easily parse it with Gson. example here

How to parse JSON without title object in Android?

I've a json output which returns something like this :
[
{
"title":"facebook",
"description":"social networking website",
"url":"http://www.facebook.com"
},
{
"title":"WoW",
"description":"game",
"url":"http://us.battle.net/wow/"
},
{
"title":"google",
"description":"search engine",
"url":"http://www.google.com"
}
]
I am familiar with parsing json having the title object, but i've no clue about how to parse the above json as it is missing the title object. Can you please provide me with some hints/examples so i can check them and work on parsing the above code?
Note : I've checked a similar example here but it doesn't have a satisfactory solution.
Your JSON is an array of objects.
The whole idea around Gson (and other JSON serialization/deserialization) libraries is that you wind up with your own POJOs in the end.
Here's how to create a POJO that represents the object contained in the array and get a List of them from that JSON:
public class App
{
public static void main( String[] args )
{
String json = "[{\"title\":\"facebook\",\"description\":\"social networking website\"," +
"\"url\":\"http://www.facebook.com\"},{\"title\":\"WoW\",\"description\":\"game\"," +
"\"url\":\"http://us.battle.net/wow/\"},{\"title\":\"google\",\"description\":\"search engine\"," +
"\"url\":\"http://www.google.com\"}]";
// The next 3 lines are all that is required to parse your JSON
// into a List of your POJO
Gson gson = new Gson();
Type type = new TypeToken<List<WebsiteInfo>>(){}.getType();
List<WebsiteInfo> list = gson.fromJson(json, type);
// Show that you have the contents as expected.
for (WebsiteInfo i : list)
{
System.out.println(i.title + " : " + i.description);
}
}
}
// Simple POJO just for demonstration. Normally
// these would be private with getters/setters
class WebsiteInfo
{
String title;
String description;
String url;
}
Output:
facebook : social networking website
WoW : game
google : search engine
Edit to add: Because the JSON is an array of things, the use of the TypeToken is required to get to a List because generics are involved. You could actually do the following without it:
WebsiteInfo[] array = new Gson().fromJson(json, WebsiteInfo[].class);
You now have an array of your WebsiteInfo objects from one line of code. That being said, using a generic Collection or List as demonstrated is far more flexible and generally recommended.
You can read more about this in the Gson users guide
JSONArray jsonArr = new JSONArray(jsonResponse);
for(int i=0;i<jsonArr.length();i++){
JSONObject e = jsonArr.getJSONObject(i);
String title = e.getString("title");
}
use JSONObject.has(String name) to check an key name exist in current json or not for example
JSONArray jsonArray = new JSONArray("json String");
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonobj = jsonArray.getJSONObject(i);
String title ="";
if(jsonobj.has("title")){ // check if title exist in JSONObject
String title = jsonobj.getString("title"); // get title
}
else{
title="default value here";
}
}
JSONArray array = new JSONArray(yourJson);
for(int i = 0 ; i < array.lengh(); i++) {
JSONObject product = (JSONObject) array.get(i);
.....
}

Android: Divide one String into 2 String values from responseBody

With this function I got a String from the server as a response:
String responseBody = EntityUtils.toString(response.getEntity());
the String value I retrieve looks more or less like this:
"http://url.com 765889"
I want to divide the URL and the numbers into 2 String values, it should be:
String 1="http://url.com"
String 2="765889"
How am I able to perform that?
Use the split() function:
String[] parts = responseBody.split(" ");
Maybe like this
String 1 = responseBody.substring(0,responseBody.indexOf(" ")-1);
String 2 = responseBody.substring(responseBody.indexOf(" ").responseBody.length()-1);
Simples do this
StringTokenizer t = new StringTokenizer("http://url.com 765889"," ");
Log.d("first", t.nextToken());
Log.d("second", t.nextToken());

Categories

Resources