Example of class that will hold the properties in JSONObject and then return the object properties
class OperatorProperties {
JSONObject TigoProperties()
{
JSONObject property = new JSONObject();
try {
property.put("color", "#223f99");
property.put("logo", R.drawable.tigo);
}catch (JSONException e){
e.printStackTrace();
}
return property;
}
}
Problems, I don't know how to get the properties details from the JSONObejct
JSONObject d = OperatorProperties.TigoProperties();
operatorLogo.setImageResource(d);
Any help please because am just want every property should come from the JSONObject
Related
private static JSONArray getListOfChildPagesAsJSON(Page page) {
JSONArray pagesArray = new JSONArray();
try {
Iterator<Page> childPages = page.listChildren();
while (childPages.hasNext()) {
Page childPage = childPages.next();
JSONObject pageObject = new JSONObject();
pageObject.put(childPage.getTitle(), childPage.getPath());
pagesArray.put(pageObject);
}
} catch (JSONException e) {
LOG.error(e.getMessage(), e);
}
return pagesArray;
}
So that not only the children of the transferred page put into array, but also the children of the children.
This is a classical case for recursion, like reading directoy tree on filesystem. My suggestion is as follows:
First step: Change the scope of variable JSONArray pagesArray = new JSONArray(); from function to class scope.
public MyClass {
private JSONArray pagesArray = new JSONArray();
...
}
Step two: Change return value to void and the modifier of your function by removing static.
private void getListOfChildPagesAsJSON(Page page) { }
Step three add the missing recusion to your its body.
//JSONArray pagesArray = new JSONArray();
try {
Iterator<Page> childPages = page.listChildren();
while (childPages.hasNext()) {
Page childPage = childPages.next();
JSONObject pageObject = new JSONObject();
pageObject.put(childPage.getTitle(), childPage.getPath());
//Add the created object to your array which is class variable
this.pagesArray.put(pageObject);
//--Check for each single page for child pages again
Iterator<Page> childPagesOfChildpage = childPage.listChildren();
while (childPagesOfChildpage.hasNext()) {
getListOfChildPagesAsJSON(childPagesOfChildpage.next());
}
//--
}
} catch (JSONException e) {
LOG.error(e.getMessage(), e);
}
Note: The check childPage.hasChild() does not work here, because the node jcr:content is a valid child of passed page.
I am developing a java application in android studio and a Rest web server in java, netbeans.
I need to send a JSON to the server ...
I did the whole engine the webService and tested it using Postman.
The Json used was this:
{
"id":0,
"ticket":"2132158645161654561651616",
"avaliacoes":[
{
"idAvaliacao":1,
"nota":5,
"observacao":"testeTEste"
},
{
"idAvaliacao":2,
"nota":4,
"observacao":"testeTEste"
}
]
}
Worked perfectly.
So I went to generate Json dynamically in the application:
public void enviaDadosVenda(){
JSONObject obj = new JSONObject();
JSONArray avaliacoes = new JSONArray();
JSONObject avaliacao;
try {
obj.put("id", 0);
obj.put("ticket", PrincipalActivity.ticket_id);
for(int i=0; i < PrincipalActivity.listAval.size();i++){
avaliacao = new JSONObject();
avaliacao.put("idAvaliacao", listAval.get(i).getId());
avaliacao.put("nota", listAval.get(i).getNota());
avaliacao.put("observacao", listAval.get(i).getObservacoes());
avaliacoes.add(avaliacao);
}
obj.put("avaliacoes", avaliacoes);
} catch (JSONException e) {
e.printStackTrace();
}
}
The generated Json is this:
{
"id":0,
"ticket":"2132158645161654561651616",
"avaliacoes":"[
{
\"idAvaliacao\":1,
\"nota\":5,
\"observacao\":\"testeTEste\"
},
{
\"idAvaliacao\":2,
\"nota\":4,\"observacao\":\"testeTEste\"
}
]"
}
If I use this second Json on Postman the webService no gets it correctly.
Get the id and the ticket, but the evaluations array gets a single item(avaliacoes.get(0)) = null.
I've looked at other posts about Json and ArrayJsons and nothing helped me ...
Parsing JSON Object in Java
Convert JsonObject to String
How to create correct JSONArray in Java using JSONObject
https://pt.stackoverflow.com/questions/140442/reconhecer-um-jsonobject-ou-jsonarray
Just replace avaliacoes.add(avaliacao); with avaliacoes.put(avaliacao);
public void enviaDadosVenda(){
JSONObject obj = new JSONObject();
JSONArray avaliacoes = new JSONArray();
JSONObject avaliacao;
try {
obj.put("id", 0);
obj.put("ticket", "DemoActivity.ticket_id");
for(int i=0; i < 2;i++){
avaliacao = new JSONObject();
avaliacao.put("idAvaliacao", "1");
avaliacao.put("nota", "nota");
avaliacao.put("observacao", "observacao");
avaliacoes.put(avaliacao);
}
obj.put("avaliacoes", avaliacoes);
Log.d("DEMO", obj.toString()); // {"id":0,"ticket":"DemoActivity.ticket_id","avaliacoes":[{"idAvaliacao":"1","nota":"nota","observacao":"observacao"},{"idAvaliacao":"1","nota":"nota","observacao":"observacao"}]}
} catch (JSONException e) {
e.printStackTrace();
}
}
For best practice use Gson
I am new to Android and JAVA and I am trying to parse a json response. I know how to parse jsonarray but no Idea how to parse jsonobject. Can someone tell me how? Below is my Response.
{"118":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"},"119":{"garment_color":"hjsadjjs","garment_name":"sdasd","garment_price":"23478"}}
And this is how parsed jsonarray.
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.INVISIBLE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
//GetDataAdapter2.setImageServerLarger(json.getString(JSON_IMAGE_LARGER));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
GetDataAdapter2.setMrp_price(json.getString(JSON_MRP_PRICE));
GetDataAdapter2.setDisc_price(json.getString(JSON_DISC_PRICE));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
Please Someone help. Thanks.
In my opinion, use Gson library, where you give it the json object/array/string and it automatically parses it into a java object. Note that you have to define the java class with the appropriate fields.
EDIT: So here's an answer that goes with the suggested guidelines:
First create your model classes just like you will receive them from the server:
public class MyServerObject {
MyGarment jsonKeyName;
}
public class MyGarment {
String garment_color;
String garment_name;
String garment_price;
}
Next, after receiving your json string, parse it using Gson:
Gson gson = new Gson();
String json= "{"jsonKeyName":{"garment_color":"Blue","garment_name":"skjhkds","garment_price":"232"};
MyServerObject serverObject = gson.fromJson(json, MyServerObject.class);
Now, you can access your Garment object from your server object with all the values parsed correctly. Also note that if you're receiving a json array you could add the object as a list in your MyServerObject.class.
Hope this helps.
as per my above comment
you need to make JSONObject request instead of JSONArray request
try this to parse your JSON Response
try {
JSONObject jsonObject= new JSONObject("Response");
JSONObject jsonObject1=jsonObject.getJSONObject("118");
String garment_color=jsonObject1.getString("garment_color");
String garment_name=jsonObject1.getString("garment_name");
String garment_price=jsonObject1.getString("garment_price");
JSONObject jsonObject2=jsonObject.getJSONObject("119");
String garment_color2=jsonObject1.getString("garment_color");
String garment_name2=jsonObject1.getString("garment_name");
String garment_price2=jsonObject1.getString("garment_price");
} catch (JSONException e) {
e.printStackTrace();
}
Use StringRequest instead of JSONObject/JSONArray request and finally fetch value like this:
JSONObject object = new JSONObject(YOUR JSON RESPONSE);
String s1 = object.getJSONObject("118").getString("garment_color");
I have json data format like
{
"status":200,
"message":"ok",
"response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0]
}
}
I want to get one value of values array and put it on textView in eclipse. Look my code in eclipse
protected void onPostExecute (String result){
try {
JSONobject json = new JSONObject(result);
tv.setText(json.toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
You can use GSON
Create a POJO for your response
public class Response{
private int result;
private double time;
private ArrayList<Integer> values;
// create SET's and GET's
}
And then use GSON to create the object you desire.
protected void onPostExecute (String result){
try {
Gson gson = new GsonBuilder().create();
Response p = gson.fromJson(result, Response.class);
tv.setText(p.getValues());
}catch (JSONException e){
e.printStackTrace();
}
}
You can use jackson library for json parsing.
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readTree(json);
map.get("key");
You can use readTree if you know json is an instance of JSONObject class else use typeref and go with readValue to get the map.
protected void onPostExecute (String result){
try {
JSONObject json = new JSONObject(result);
JSONObject resp = json.getJSONObject("response");
JSONArray jarr = resp.getJSONArray("values");
tv.setText(jarr.get(0).toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
I have a bundle that I would like to convert to one big JSONObject so that I can send it through a web service later on. This main bundle contains mainly strings and integers, but it also contains another bundle, which in that contains bundles that have sets of 4 key value pairs.
Here is a diagram to clear up any confusion:
Code:
private JSONObject convertBundleToJSON(Bundle b)
{
//the main json object to be returned
JSONObject json = new JSONObject();
Set<String> keys = b.keySet();
for (String key : keys) {
try {
// json.put(key, bundle.get(key)); see edit below
json.put(key, JSONObject.wrap(b.get(key)));
} catch(JSONException e) {
//Handle exception here
Log.d("Convert Bund", e.toString());
}
}
JSONObject fvl = new JSONObject();
int i = 0;
//error right here - b is a bundle of bundles; trying to iterate through
Set<Bundle> bundles = (Set<Bundle>) b.get("field_value_list");
for (Bundle bun : bundles)
{
JSONObject f = new JSONObject();
try {
f.put("fld_value_decode", bun.get("fld_value_decode"));
f.put("fld_id", bun.get("fld_id"));
f.put("fld_value", bun.get("fld_value"));
f.put("fld_name", bun.get("fld_name"));
fvl.put(i+"",f);
i++;
} catch(JSONException e) {
//Handle exception here
Log.d("FVL Convert Bund", e.toString());
}
}
try {
json.put("field_value_list", fvl);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
But I get a casting exception at the error line. It doesn't like the cast between bundle and set. Any ideas or alternative ways to get around this?
Rather than doing this sophisticated way, you can simply achieve this by creating a model class which is parcelable.
Simply add those json to that model and further passing it, using it would be simpler.