Getting String from Json? - android

I have a strange problem in my android app. In one method I do this :
try {
String r = responseBody.toString();
JSONArray jArray = new JSONArray(r);
categorys = new String[jArray.length()];
idcategory = new Integer[jArray.length()];
System.out.println("lung " + jArray.length());
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsdata = jArray.getJSONObject(i);
String idcat = jsdata.getString("id_category");
idcategory[i] = Integer.valueOf(idcat);
System.out.println("Id " + idcat);
String namecategory = jsdata.getString("category_name");
categorys[i] = namecategory;
System.out.println("Category name " + namecategory);
}
and everything works fine, I get from server the categorys and category's id. In an other method I do this (for an other response) :
try {
String re = responseBody.toString();
JSONArray jArray = new JSONArray(re);
System.out.println("lung " + jArray.length());
titlephotos = new String[jArray.length()];
photolink=new String[jArray.length()];
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsdata = jArray.getJSONObject(i);
String titlephoto = jsdata.getString("title");
System.out.println("titlu photo " + titlephoto);
titlephotos[i] = titlephoto;
String linkphoto=jsdata.getString("view");
System.out.println("link photo"+ linkphoto);
photolink[i]=linkphoto;
}
}catch(JSONException e) {
System.out.println("You are in catch");
}
and I get only one title photo an after that I get the message from catch(). If I don't put
String linkphoto=jsdata.getString("photo link");
System.out.println("link photo"+ linkphoto);
photolink[i]=linkphoto;
I get all the titles. I don't understand where is the problem,because the methods are similar, and the first one works fine. Can anyone help?
Thanks...

Most likely it is the space in
String linkphoto=jsdata.getString("photo link");

Related

Convert JSONArray string value into int value

I need to convert the value from key "Quantity" into a int.
Basically I have this:
[{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]
Need to convert to this:
[{"Code":"NV","Quantity":333},{"Codigo":"NV","Quantity":333}]
How can I do it?
Assuming your json data in string and setting it in data string
String data = "[{\"Code\":\"NV\",\"Quantity\":\"333\"},{\"Code\":\"NV\",\"Quantity\":\"333\"}]";
try {
JSONArray jsonArray = new JSONArray(data);
Log.d(TAG, "Old JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int quantityValue = Integer.parseInt(jsonObject.getString("Quantity"));
jsonObject.put("Quantity", quantityValue);
}
Log.d(TAG, "New JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":333},{"Code":"NV","Quantity":333}]
} catch (JSONException e) {
e.printStackTrace();
}
What I am doing here is just replacing old Quantity string value with int value by using Integer.parseInt()
Please try the following:
for(int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
object.put("Quantity", Integer.parseInt(object.getString("Quantity")));
}
You will need to replace array with the name of your array.

how to get json which has multiple values in a string in android

I have a json which has multiple values separated by commas which is in the
form of array.I want to get skills and platforms string separately.Can you please help me?
I want to show skills string and platforms string in text.
Please help me.
The format is:
{
"data": [
{
"skills": "ANDROID SDK, ANIMATION, ANGULARJS,",
"platforms": "IOS Application, Social Networking, Online shopping Sites, Web Application"
}
],
"status": 100
}
Try this one
try {
JSONObject ob = new JSONObject(response);
int status = ob.getInt("status");
if (status == 100) {
JSONArray ja = ob.getJSONArray("data");
for (int i = 0; i < ja.length(); i++) {
values = new HashMap<>();
JSONObject vj = ja.getJSONObject(i);
String skills = vj.getString("skills "));
String platforms=vj.getString("platforms"));
data.add(values);
}
split these 2 strings using 'split()'
List<String> skillsArray = Arrays.asList(skills.split(","));
List<String> platformsArray= Arrays.asList(platforms.split(","));
String in = "your json";
JSONObject jsonObj = new JSONObject(in);
// Getting JSON Array node
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Try this
JSONObject jsonObject = new JSONObject("Your json response");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skill = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
String[] skillsArray = skill.split(Pattern.quote(","));
String[] platformsArray = platforms.split(Pattern.quote(","));
for (int j=0; j<skillsArray.length; j++)
{
Log.i("Skill Value ", "=" + skillsArray[j]);
}
for (int j=0; j<platformsArray.length; j++)
{
Log.i("platforms Value ", "=" + platformsArray[j]);
}
}
Output
First of all convert your output string into json. Note that output string is the string which contains your results of json format that you have posted above.following is the code on how to do that:
JSONObject myJsonResponse = new JSONObject(yourString);
The next one is Array. That is how you will get it and will iterate over it.
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject innerJsonObject= jsonarray.getJSONObject(i);
String skills = innerJsonObject.getString("skills");
String platforms = innerJsonObject.getString("platforms");
}
Now you have gotten your required fields and you can now perform any String functions over the String skills and platforms.
Happy coding. .
The best way is creating a model class such :
public class MyModel{
Properties [] data;
class Properties{
public String skills;
public String platforms;
}
}
then you can parse your string to model with Gson library like this :
MyModel myModel = new Gson().fromJson(yourString, MyModel.class)
so all data is in myModel object and you can access to skills with
myModel.data[0].skills
to add Gson library to your project add below to your app gradle file :
compile 'com.google.code.gson:gson:2.8.1'
You may try this,
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject("JSON_STRING");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String[] seperateData = skills.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Skill Value-> ", seperateData[j]);
}
String platforms = jsonobject.getString("platforms");
seperateData = platforms.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Platform Value-> ", seperateData[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
class Data{
public String skills;
public String platforms;
}
Gson gson = new Gson();
JSONArray dataArray = response.getJSONArray("data");
List<Data> dataList= gson.fromJson(dataArray toString(), new TypeToken<List<Data>>() {
}.getType());
Try this.. It will make parsing easier.
implementation 'com.google.code.gson:gson:2.8.0'
First Parse your JSON:
JSONObject jsonObj = new JSONObject(in);
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Then Split your string values:
String skills = "ANDROID SDK, ANIMATION, ANGULARJS";
String[] separated = CurrentString.split(",");
separated[0]; // this will contain "ANDROID SDK"
separated[1]; // this will contain " ANIMATION"
separated[2]; // this will contain " ANGULARJS"
You have to remove the space to the second String:
separated[1] = separated[1].trim();
Try this you will be getting all values of sapereted with commas
jsonString = getting string from server side
String[] separated = jsonString.split(",");
StringBuilder s = new StringBuilder(10000);
for (int i = 0; i < separated.length; i++) {
if (i == separated.length - 1) {
s.append(separated[i].trim() + "");
} else {
s.append(separated[i].trim() + ",\n");
}
}
//tvDisplayAddress.setText(s);
Log.e("VALUES: ",s+"");

Decode JSON String in Android

I have a contacts which is in the form of JSON. Now I want to decode them into String array. There are two arrays; names and phones. I'm using this code:
String[] names;
String[] phones;
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
JSONObject jsonObject = new JSONObject(jsonArray.toString());
Log.i("INFO", String.valueOf(jsonObject.length()));
} catch (JSONException e) {
e.printStackTrace();
}
This generates an error. How can I add all names in names array and all phones in phones array. Like names[0] is assigned A which is a first name and phones[0] assigned 911 which is first phone number corresponding to first name. How can I do that, I'm new in android?
The problem is in this line
JSONObject jsonObject = new JSONObject(jsonArray.toString());
you are trying to convert JSONArray in JSONObject , which you can't. if you want to access JSONObject inside of JSONArray you have to loop through each, or you can get specific object by it's index.
String[] names;
String[] phones;
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
phones = names = new String[jsonArray.length()];
for(int i = 0 ; i < jsonArray.length(); i ++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
names[i] = jsonObject.getString("name");
phones[i] = jsonObject.getString("phone");
Log.i("INFO", "name : " + jsonObject.getString("name") + " , phone : " + jsonObject.getString("phone"));
}
} catch (JSONException e) {
e.printStackTrace();
}
You can't convert json arrya to json object like that:
try {
JSONArray jsonArray = new JSONArray(test);
for(int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Your code goes here..
}
} catch (JSONException e) {
e.printStackTrace();
}
here is the required code.
ArrayList<String> names = new ArrayList<>();
ArrayList<String> phones = new ArrayList<>();
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String phone = jsonObject.getString("phone");
names.add(name);
phones.add(phone);
Log.i("INFO", name + ", " + phone);
}
} catch (JSONException e) {
e.printStackTrace();
}
above you have used simple arrays they can store data only of fixed size. But arrayList and List can store data of variable size or you do not need to fix their size.

How to parse this JSON in to string in android?

Can someone show me how to write this json into a code?
Is it correct if I get this json data as json object first and the loop the jsonarray in the try catch block in android?
{"charges":[{"Fhour":"0.3","Shour":"0.2","Rhours":"0.1"}]}
Kindly help me thanks in advance
Your String can be parsed like
String json = "{\"charges\":[{\"Fhour\":\"0.3\",\"Shour\":\"0.2\",\"Rhours\":\"0.1\"}]}";
JSONObject jsonObject = new JSONObject(json);
JSONArray charges = jsonObject.getJSONArray("charges");
for (int i = 0; i < charges.length(); i++) {
JSONObject c = charges.get(i);
String fHour = c.getString("Fhour");
String sHour = c.getString("Shour");
String rHours = c.getString("Rhours");
Log.d("(f,s,r)Hours : ", "(" + fHour + "," + sHour + "," + rHours + ")");
}
Use built-in JSON library.
JSONObject buddiesDoc = new JSONObject(result);
JSONArray buddies = buddiesDoc.getJSONArray("buddies");
for (int n = 0; n < buddies.length(); n++) {
JSONObject object = buddies.getJSONObject(n);
object.getString(BuddyManager.CACHED_BUDDY_KEY_CONTACTID);
...

About android JSON parser

I have a long string from android Http get like this:
{"movies":[
{"movieId":"fmen71229238","eTitle":"Mission: Impossible - Ghost Protocol","cTitle":"不可能的任務:鬼影行動","imageUrl":"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fmen7122923814_s.jpg","releaseDate":"2011/12/15","saleType":"0"},
{"movieId":"fstw79905171","eTitle":"Seediq Bale","cTitle":"賽德克.巴萊(上)太陽旗","imageUrl":"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fstw7990517114_s.jpg","releaseDate":"2011/9/9","saleType":"0"},
{"movieId":"fytw91390391","eTitle":"You Are the Apple of My Eye","cTitle":"那些年,我們一起追的女孩","imageUrl":"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fytw9139039102_s.jpg","releaseDate":"2011/8/19","saleType":"0"}
]}
the string is JSON format, and I want it be sort in different array,and display in a Listview, so I used the JSON paser like this
JSONArray result = new JSONArray(retSrc);
for(int i = 0;i < result.length(); i++)
{
JSONObject stock_data = result.getJSONObject(i);
Log.i("bird","eTitle:"+stock_data.getString("eTitle"));
}
} finally {
}
}
p.s retSrc is the long string from site
But the Log
Log.i("bird","eTitle:"+stock_data.getString("eTitle"));
logs nothing.
I expect it log like this:
Mission: Impossible - Ghost Protocol Seediq Bale.....etc
here is the code to parse it
String jsonData = "{\"movies\":["
+ "{\"movieId\":\"fmen71229238\",\"eTitle\":\"Mission: Impossible - Ghost Protocol\",\"cTitle\":\"??????:????\",\"imageUrl\":\"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fmen7122923814_s.jpg\",\"releaseDate\":\"2011/12/15\",\"saleType\":\"0\"},"
+ "{\"movieId\":\"fstw79905171\",\"eTitle\":\"Seediq Bale\",\"cTitle\":\"???.??(?)???\",\"imageUrl\":\"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fstw7990517114_s.jpg\",\"releaseDate\":\"2011/9/9\",\"saleType\":\"0\"},"
+ "{\"movieId\":\"fytw91390391\",\"eTitle\":\"You Are the Apple of My Eye\",\"cTitle\":\"???,????????\",\"imageUrl\":\"http://test.mobibon.com.tw/MovieGoTest/Pics/pl_fytw9139039102_s.jpg\",\"releaseDate\":\"2011/8/19\",\"saleType\":\"0\"}"
+ "]}";
JSONObject jsonObj = new JSONObject(jsonData);
JSONArray movieArray = jsonObj.getJSONArray("movies");
JSONObject movieObj = null;
for (int i = 0; i < movieArray.length(); i++) {
movieObj = movieArray.optJSONObject(i);
if (null != movieObj) {
String mId = movieObj.optString("movieId");
String title = movieObj.optString("eTitle");
String cTitle = movieObj.optString("cTitle");
String imageUrl = movieObj.optString("imageUrl");
String releaseDate = movieObj.optString("releaseDate");
String saleType = movieObj.optString("saleType");
System.out.println("movieID [" + mId + "] eTitle [" + title
+ "] cTitle [" + cTitle + "] imgUrl [" + imageUrl
+ "] relDate [" + releaseDate + "] saleType ["
+ saleType + "]");
}
You can also make use of Gson, which provides you api's for Json parsing. its very easy just you need to create type of object you want.
Obviously, the top level of the json file is not a JSONArray but a JSONObject.
Use something like following:
JSONObject obj = new JSONOBject(retSrc);
JSONArray movieArray = obj.getJSONArray("movies");
//then process the movie as you did

Categories

Resources