I know how to parse json but I can not solve integer json field in this json. Because this json contain integer field(23254,23998).
Here my JSON
{
"status":"OK",
"alarms":{
"23254":[
{
"speed_limit":250,
"acc_limit":null,
"dcc_limit":null,
"idle_limit":null
}
],
"23998":[
{
"speed_limit":120,
"acc_limit":null,
"dcc_limit":null,
"idle_limit":null
}
]
}
}
try{
JSONObject j=new JSONObject("here put your response string");
JSONObject j1= j.getJSONObject("alarms");
ArrayList<String> arr=new ArrayList<String>();
Iterator iter = j1.keys();
while(iter.hasNext()){
String key = (String)iter.next();
arr.add(j1.getJSONArray(key).toString());
System.out.println("json"+j1.getJSONArray(key).toString());
}
}catch (JSONException e){
e.printStackTrace();
}
Parse the Json object like this way
JSONObject obj= new JSONObject(content);
Iterator iterator = obj.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
JSONObject object1 = obj.getJSONObject(key);
// get id from object1
String _pubKey = object1.optString("id");
}
Related
I have json data as mentioned below.
{
"data":[
{
"Products":{
"id":"86",
"pname":"mi4",
"pcat":"9",
"subcat":"8",
"seccat":"0",
"oproduct":"1",
"pdetails":"Good phone",
"pprice":"10000",
"pdiscount":"10",
"qty":"1",
"qtytype":"GM",
"dcharge":"40",
"pimage":null,
"sname":"Easydeal",
"sid":"1100",
"size":"",
"pincode":""
}
}
]
}
I can identify array as getJSONArray("datas"). But I want to get pname and sname values.
Just reach the object
JSONObject resp=new JSONObject("response");
JSONArray data=resp.getJSONArray("data");
now if you want to get object at a particular index(say '0')
JSONObject objAt0=data.getJSONObject(0);
JSONObject products=objAt0.getJSONObject("products");
String pName=products.getString("pname");
you can similarly traverse the array
for(int i=0;i<data.lenght();i++){
JSONObject objAtI=data.getJSONObject(i);
JSONObject products=objAtI.getJSONObject("products");
String pName=products.getString("pname");
}
To get the to the key "Products" you should do:
JSONObject productsObject = YOUROBJECTNAME.getJSONArray("data").getJSONObject(0).getJSONObject("Products");
Then to get the values in productsObject you should do:
productsObject.getString("id");
productsObject.getString("pdetails");
And so on.
Try out the following code:
JSONObject object = new JSONObject(result);
JSONArray array = object.getJSONArray("data");
JSONObject object1 = array.getJSONObject(0);
JSONObject products = object1.getJSONObject("Products");
int id = object1.getInt("id");
String pname = object1.getString("pname");
This is how you get pname and sname:
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray;
try {
jsonArray = jsonObject.getJSONArray("data");
for(int counter = 0; counter <jsonArray.length(); counter++){
JSONObject jsonObject1 = jsonArray.getJSONObject(counter);
JSONObject products = jsonObject1.getJSONObject("Products");
String pname = products.getString("pname");
String sname = products.getString("sname");
}
} catch (JSONException e) {
e.printStackTrace();
}
PS: Poor JSON structure :)
I have JSON code like above, as a response:
"candidates": [
{
"subtest1": "0.802138030529022",
"enrollment_timestamp": "1416850761"
},
{
"elizabeth": "0.802138030529022",
"enrollment_timestamp": "1417207485"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416518415"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416431816"
}
]
I try to get names from candidates array.
public void dataCheck(String text){
System.out.println("JSON response:");
System.out.println(text);
try {
JSONObject jsonRootObject = new JSONObject(text);
JSONArray jsonArray = jsonRootObject.optJSONArray("candidates");
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String subtest1 = jsonObject.optString("subtest1").toString();
}
} catch (JSONException e){
e.printStackTrace();
}
}
It is hard, because these values are in an array of an array and without identifier. Identifier is the exact value, so couldn't define variable in my code. I need only first value, like subtest1 in this example.
// Get the keys in the first JSON object
Iterator<?> keys = jsonObject.keys();
if (keys.hasNext()) {
// Get the key
String key = (String)keys.next();
String objValue = jsonObject.getString(key);
...
}
I want to send Json Parameters (below) in Android - POST Method.
{"message":"This is venkatesh","visit":[5,1,2]}
I tried the below code
String IDs="5,1,2";
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "This is venkatesh");
JSONArray jsonArray = new JSONArray();
jsonArray.put(IDs);
jsonObject.put("visit", jsonArray);
String json = jsonObject.toString();
Log.d("Mainactivity", " json" + json);
I am getting the output is
{"message":"This is venkatesh","visit":["5,1,2"]}
// Output i am get with double quotes inside visit
{"message":"This is venkatesh","visit":[5,1,2]}
// I want to send this parameter without Double quotes inside the Visit
String IDs="5,1,2";
String[] numbers = IDs.split(",");
JSONArray jsonArray = new JSONArray();
for(int i = 0; i < numbers.length(); i++)
{
jsonArray.put(Integer.parseInt(numbers[i]));
}
Hope this helps.
In array add it as integer not as a String
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("message", "This is venkatesh");
JSONArray jsonArray = new JSONArray();
jsonArray.put(5);
jsonArray.put(1);
jsonArray.put(2);
jsonObject.put("visit", jsonArray);
String json = jsonObject.toString();
Log.i("TAG", " json" + json); //{"message":"This is venkatesh","visit":[5,1,2]}
} catch (JSONException e) {
e.printStackTrace();
}
Just replace following line:
jsonArray.put(IDs);
with following code:
jsonArray.put(5);
jsonArray.put(1);
jsonArray.put(2);
So you should use 'int' values if you want to see array without quotes. The point is 'quotes' means that this is String object. Proof is following line of your code:
String IDs="5,1,2";
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "This is venkatesh");
JSONArray jsonArray = new JSONArray(new int[](5, 1, 2));
jsonObject.put("visit", jsonArray);
I am assuming you will convert the String to integer array and after you do this is how you can add,
Well the only difference you need to understand is that, JSON adds double quotes for values of String and not of Integer.
so for Key value pair for String it would be
"key":"value"
so for Key value pair for Integer it would be
"key":123
so for Key value pair for boolean it would be
"key":true
With that knowledge you can edit your code.
Code
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", "This is venkatesh");
JSONArray jsonArray = new JSONArray();
jsonArray.put(0,5);
jsonArray.put(1,1);
jsonArray.put(2,2);
jsonObject.put("visit", jsonArray);
Log.d("TAG","result "+jsonObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
Output
{"message":"This is venkatesh","visit":[5,1,2]}
int[] arrayOfInteger=[1,2,3];
JSONObject jsonObject =new JSONObject();
jsonObject .put("message","your message");
JSONArray jsonArray = new JSONArray(arrayOfInteger);
jsonObject .put("visit",jsonArray );
Result : {"message":"your message","visit":[1,2,3]}
My String contains json
result=[{"USER_ID":83,"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"},{"USER_ID":88,"PROJECT_BY_DETAILS":"Test - over ye mountain blue "}]
How to create JSONOBject and JSONarray from this string
I used this code
JSONObject json =new JSONObject(result);
//Get the element that holds the earthquakes ( JSONArray )
JSONArray earthquakes = json.getJSONArray("");
i got error
Error parsing data org.json.JSONException: Value [{"USER_ID":83,"PRO
If it starts with [ its an array, try with:
JSONArray json =new JSONArray(result);
Difference between JSONObject and JSONArray
use this code for your JsonArray:
try {
JSONArray json = new JSONArray(YOUR_JSON_STRING);
for (int i = 0; i < json.length(); i++) {
JSONObject jsonDATA = json.getJSONObject(i);
String jsonid = jsonDATA.getInt("USER_ID");
String jsondetails = jsonDATA.getString("PROJECT_BY_DETAILS");
}
} catch (JSONException e) {
return null;
}
use Gson for you to do that.
That Json response is an array you know it because of the square brackets [].
Create a mapping object (a java class) with field USER_ID and PROJECT_BY_DETAILS.
public class yourClass(){
public String USER_ID;
public String PROJECT_BY_DETAILS;
}
Create a Type array like so.
final Type typeYourObject = new TypeToken>(){}.getType();
define your list private
List yourList;
Using Gson you will convert that array to a List like so
yourList = gson.fromJson(yourJson, typeYourObject);
with that list later you can do whatever you want. Also with Gson convert it back to JsonArray or create a customs JsonObject.
According to my understanding the JSON object looks like this,
{
"RESULT":[
{
"USER_ID":83,
"PROJECT_BY_DETAILS":"An adaptation of a nursery rhyme into a dramatic film"
},
{
"USER_ID":88,
"PROJECT_BY_DETAILS":"Test - over ye mountain blue "
}
]
}
You are converting this to a String and you wish to re-construct the JSON object. The decode function in the android-side would be this,
void jsonDecode(String jsonResponse)
{
try
{
JSONObject jsonRootObject = new JSONObject(jsonResponse);
JSONArray jData = jsonRootObject.getJSONArray("RESULT");
for(int i = 0; i < jData.length(); ++i)
{
JSONObject jObj = jData.getJSONObject(i);
String userID = jObj.optString("USER_ID");
String projectDetails = jObj.optString("PROJECT_BY_DETAILS");
Toast.makeText(context, userID + " -- " + projectDetails,0).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
I am geting JSON data getting from web service. Below is my code.
How can I decode the json data?
{
"response": [
{
"last_name": "Test",
"id": 279711390,
"first_name": "Vishnu",
"sex": 2,
"photo_50": "https://vk.com/images/camera_50.gif"
}
]
}
How can I parse it? Thanks.
You can keep a POJO class. With the data which you are about to get from server. And parse them and save in that object.
Example:
JSONObject json= new JSONObject(responseString); //your response
try {
JSONArray responseArray = jsonObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
// get value with the NODE key
JSONObject obj = responseArray.getJSONObject(i);
String lastName = obj.getString("last_name");
String firstName = obj.getString("first_name");
//same for all other fields in responseArray
MyResponse myResp = new MyResponse();
myResp.setFirstName(firstName);
myResp.setLastName(lastName);
//set all other Strings
//lastly add this object to ArrayList<MyResponse> So you can access all data after saving
}
}
catch (JSONException e) {
e.printStackTrace();
}
POJO Class:
public class MyResponse{
public String firstName="";
public String lastName="";
//all other fields and getter setters
}
Hope this helps.
You can parse JSON using this code:
str="<The Json>"
try {
JSONObject jObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getString("response"));
String lastName;
for (int i = 0; i<menuObject.length(); i++) {
lastName=menuObject.getJSONObject(i).getString("last_name").toString();
...
}
catch (JSONException e) {
e.printStackTrace();
}
Use this code :-
String string = "Your Json"
try {
JSONObject jsonObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getJsonArray("response"));
//no need of for loop because you have only one object in jsonArray.
JSONObject oject = menuObject.getJSONObject(0);
String lastName = object.getString("last_name");
String firstName = object.getString("first_name");
Log.d("User Name", firstName + " " + lastName);
catch (JSONException e) {
e.printStackTrace();
}