How to generate JsonArray correctly? - java

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

Related

Accessing the JSON data from the method in android

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

Parsing JsonObjectRequest

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");

Deserialize classes with same interface using GSON

I have an interface (called Content) and a couple of classes that implement that interface (e.g. ContentVideo, ContentAd...). I receive a JSON Object that contains a list of those objects. I started out deserializing those objects manually in seperate classes, but recently came across GSON, which would simplify this process immensely. But I'm not sure how to implement this.
Here's ContentVideoJSONParser
public ArrayList<ContentVideo> parseJSON(String jsonString) {
ArrayList<ContentVideo> videos = new ArrayList<>();
JSONArray jsonArr = null;
Gson gson = new Gson();
try {
jsonArr = new JSONArray(jsonString);
for(int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
ContentVideo cv = gson.fromJson(jsonObj.toString(), ContentVideo.class);
videos.add(cv);
}
} catch (JSONException e) {
e.printStackTrace();
}
return videos;
}
ContentAdJSONParser looks exactly the same, except for returning an ArrayList of ContentAd objects and this line to retrieve the object:
ContentAd ca = gson.fromJson(jsonObj.toString(), ContentAd.class);
What's the easiest way to combine those to classes into one? Note: one JSON object only contains one class, either ContentVideo or ContentAd. They are not mixed like in other SO questions, which would require a TypeAdapter.
This seems to be a straightforward problem but I can't figure it out. Thanks for your help.
Something like this perhaps?
public <T extends Content> ArrayList<T> parseJSON(String jsonString, Class<T> contentClass) {
ArrayList<T> contents = new ArrayList<>();
JSONArray jsonArr = null;
Gson gson = new Gson();
try {
jsonArr = new JSONArray(jsonString);
for(int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
T content = gson.fromJson(jsonObj.toString(), contentClass);
contents.add(content);
}
} catch (JSONException e) {
e.printStackTrace();
}
return contents;
}

parse json values using java json parser

I have a josn like this.From this how can i retrive platfrom and version values using java
code
public static void main(String[] args)
throws org.json.simple.parser.ParseException {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
josn
{
"France24":[
{
"platform":"Linux",
"version":"12.3",
}
],
"Seloger":[
{
"platform":"windows",
"version":"8",
}
],
"Marmiton":[
{
"platform":"mac",
"version":"10.1",
}
]
}
List<String> platformLst = new ArrayList<String>();
List<String> versionLst = new ArrayList<String>();
JSONArray array = obj.getJSONArray("France24");
for(int i = 0 ; i < array.length() ; i++){
JSONObject obj = array.getJSONObject(i);
versionLst.add(obj.getString("platform"));
platformLst .add(obj.getString("version"));
}
Existing Question
Example
Simple Json Tutorial Link
JSONArray jArray = jsonObject.getJSONArray("France24");
JSONObject france24Object = jArray.get(0);
String platform = france24Object.getString("platform");
String version = france24Object.getString("version");
Similarly, replace France24 with Seloger and Marmiton and repeat.
Like that:
JSONObject france = jsonObject.getJsonArray("France24").getJsonObject(0);
String platform = france.getString("platform");
String version = france.getString("version");

I can't loop through JSON Array for next Array

I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.
this for call for json
public String getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
for(int i=0;i<data.length();i++)
{
JSONObject data1 = data.getJSONObject(i);
String ans = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ans;
}
and this JSON:
{
"SearchResult": {
"next_offset": -1,
"aircraft": [
{
"ident": "AFL274",
"type": "B77W"
},
{
"ident": "CQH8971",
"type": "A320"
}
]
}
}
Try this,
public String[] getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
int arrayLength = data.length();
String[] strAryAns = new String[arrayLength];
for(int i=0;i<arrayLength;i++)
{
JSONObject data1 = data.getJSONObject(i);
strAryAns[i] = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return strAryAns;
}

Categories