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);
...
Related
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.
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+"");
I am trying to parse a JSON array from a string which I receive from the server.
Example of the array is
{"data":[{"id":703,"status":0,"number":"123456","name":"Art"}]}
I am trying to parse that using the below code which is giving me Classcast Exception which shows JSonArray can not be cast to List
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = (JSONArray) o.get("data");
Iterator i = ((List<NameValuePair>) slideContent).iterator();
while (i.hasNext()) {
JSONObject slide = (JSONObject) i.next();
int title = (Integer)slide.get("id");
String Status = (String)slide.get("status");
String name = (String)slide.get("name");
String number = (String)slide.get("number");
Log.v("ONMESSAGE", title + " " + Status + " " + name + " " + number);
// System.out.println(title);
}
What should be the correct way of parsing it?
It makes sense as a JSONArray cannot be cast to a List<>, nor does it have an iterator.
JSONArray has a length() property which returns its length, and has several get(int index) methods which allow you to retrieve the element in that position.
So, considering all these, you may wish to write something like this:
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = o.getJSONArray("data");
for(int i = 0 ; i < slideContent.length() ; i++) {
int title = slideContent.getInt("id");
String Status = slideContent.getString("status");
// Get your other values here
}
you should do like this:
JSONObject o = new JSONObject(result.toString());
JSONArray array = jsonObject.getJSONArray("data");
JSONObject jtemp ;
ArrayList<MData/*a sample class to store data details*/> dataArray= new ArrayList<MData>();
MData mData;
for(int i=0;i<array.length();i++)
{
mData = new MData();
jtemp = array.getJSONObject(i); //get i record of your array
//do some thing with this like
String id = jtemp.getString("id");
mData.setId(Integer.parseInt(id));
///and other details
dataArray.put(mData);
}
and MData.class
class MData{
private int id;
/....
public void setId(int id){
this.id = id;
}
//.....
}
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
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");