Facing issue in extracting value from nested jsonArray - java

I know a similar question has been posted, however, the answer didn't work for me.
I am new to this RestAssured.I want to get the 'uuid' value if categories equals to 'FUNGI' and feature->features conatains 'VRA'.This is my sample json:
[{
"uuid":"e223d29b-499b-b58b-995e-654bef1aab03",
"categories":[
{
"uuid":"89d1c022-4453-5f6b-883c-46730d429b2a",
"name":"FERTI"
}
],
"minRateSi":0.0
},
{
"uuid":"93015a1b-76ac-2ca3-2bbc-5ae5480962c2",
"categories":[
{
"uuid":"61c951b1-3e47-f0a0-80d8-3d43efa339fb",
"name":"FUNGI"
}
],
"minRateSi":0.0,
"maxRateSi":7.5E-8,
"features":[
{
"id":"9b4ee6b2-ae2d-6c9a-af77-08a4b749031f",
"vraMinRate":2.0E-8,
"features":[
"VRA"
]
},
{
"id":"ec0d0f52-dd71-ebb9-0a39-831768fe4490",
"vraMinRateSi":3.0E-8,
"features":[
"VRA"
]
}
]
},
{
"uuid":"38290452-4937-4f33-c54d-7f502b84ed99",
"categories":[
{
"uuid":"2c9d8cc0-01bc-899d-6782-cf412e90fd78",
"name":"FUNGI"
}
],
"maxRateSi":1.0E-7,
"features":[
{
"id":"9b4ee6b2-ae2d-6c9a-af77-08a4b749031f",
"vraMinRateSi":6.5E-8
},
{
"cropUuid":"ec0d0f52-dd71-ebb9-0a39-831768fe4490",
"vraMinRateSi":5.0E-8
}
]}]

Woo , okay your case was pretty hard to break down, but as far as you know how to use JSONArray and JSONObject classes you will be fine.
First of all let me mention how you should approach this kind of scenarios.
I prefer using an online JSON Formatter like this one simply paste your JSON payload and you will be able to tell whether to use JSONObject or JSONArray.
Please take a note here, and check out how to parse json payloads
This code will work for you, although you need to find out the logic behind it and implement JSON parsing accordingly in your future cases.
//declaring your payload
String myJsonPayload = "[{\r\n" + " \"uuid\":\"e223d29b-499b-b58b-995e-654bef1aab03\",\r\n" +
" \"categories\":[\r\n" + " {\r\n" +
" \"uuid\":\"89d1c022-4453-5f6b-883c-46730d429b2a\",\r\n" +
" \"name\":\"FERTI\"\r\n" + " }\r\n" + " ],\r\n" +
" \"minRateSi\":0.0\r\n" + " },\r\n" + " {\r\n" +
" \"uuid\":\"93015a1b-76ac-2ca3-2bbc-5ae5480962c2\",\r\n" + " \"categories\":[\r\n" +
" {\r\n" + " \"uuid\":\"61c951b1-3e47-f0a0-80d8-3d43efa339fb\",\r\n" +
" \"name\":\"FUNGI\"\r\n" + " }\r\n" + " ],\r\n" +
" \"minRateSi\":0.0,\r\n" + " \"maxRateSi\":7.5E-8,\r\n" + " \"features\":[\r\n" +
" {\r\n" + " \"id\":\"9b4ee6b2-ae2d-6c9a-af77-08a4b749031f\",\r\n" +
" \"vraMinRate\":2.0E-8,\r\n" + " \"features\":[\r\n" +
" \"VRA\"\r\n" + " ]\r\n" + " },\r\n" + " {\r\n" +
" \"id\":\"ec0d0f52-dd71-ebb9-0a39-831768fe4490\",\r\n" +
" \"vraMinRateSi\":3.0E-8,\r\n" + " \"features\":[\r\n" +
" \"VRA\"\r\n" + " ]\r\n" + " }\r\n" + " ]\r\n" + " },\r\n" +
" {\r\n" + " \"uuid\":\"38290452-4937-4f33-c54d-7f502b84ed99\",\r\n" +
" \"categories\":[\r\n" + " {\r\n" +
" \"uuid\":\"2c9d8cc0-01bc-899d-6782-cf412e90fd78\",\r\n" +
" \"name\":\"FUNGI\"\r\n" + " }\r\n" + " ],\r\n" +
" \"maxRateSi\":1.0E-7,\r\n" + " \"features\":[\r\n" + " {\r\n" +
" \"id\":\"9b4ee6b2-ae2d-6c9a-af77-08a4b749031f\",\r\n" +
" \"vraMinRateSi\":6.5E-8\r\n" + " },\r\n" + " {\r\n" +
" \"cropUuid\":\"ec0d0f52-dd71-ebb9-0a39-831768fe4490\",\r\n" +
" \"vraMinRateSi\":5.0E-8\r\n" + " }\r\n" + " ]}]";
JSONArray json = new JSONArray(myJsonPayload);
System.out.println(json);
for (int i = 0; i < json.length(); i++) {
JSONObject object = (JSONObject) json.get(i);
// System.out.println(object); // you have each JSONObject { } contained in the
// Outer JSONArray [ ]
//Getting both uuid's since you didn't answer which one.
String uuid = object.getString("uuid");
System.out.println("\n\n Next Object - Outer UUID: " + uuid);
JSONArray categories = object.getJSONArray("categories");
System.out.println(categories);
if (((JSONObject) categories.get(0)).getString("name").equalsIgnoreCase("fungi")) {
System.out.println("\nFUNGI found!:\n");
//Getting the inner UUID
String uuidOfFungi = ((JSONObject) categories.get(0)).getString("uuid");
System.out.println("Inner UUID: " + uuidOfFungi);
} else {
System.out.println("\nFUNGI NOT FOUND (ABORTING):\n");
}
// Getting Features:
try {
JSONArray featuresObject = object.getJSONArray("features");
for (int index = 0; index < featuresObject.length(); index++) {
try {
JSONObject features = featuresObject.getJSONObject(index);
//Getting VRA
String vraFeatues = features.getJSONArray("features").getString(0);
} catch (JSONException e) {
System.out.println("No inner JSONArray in features JSONObject");
}
}
} catch (JSONException e) {
System.out.println("JSON OBJECT " + i + " HAS NO FEATURES ARRAY");
}
}
Depending again on your use-case it's up to you how you will get the JSON payload into your program.
Getting it from remote URL using Java
Passing it as an argument on java -jar execution time , which i don't really recommend
Either case, modifications need to be done in order to initialize myJsonPayload accordingly.
Hope it helped!

Related

getting null JSONObject values

I'm trying to create a JSONObject as code below. But Android Studio is saying that it's null. Where is my mistake?
I tried two different ways to create it.
1st
String JSONString = "{" +
" \"retorno\": {" +
" \"empresas\": [" +
" {" +
" \"cnpj\": \"05.743.645/0001-38\"," +
" \"razao_social\": \"GISELA TRANSPORTES E DISTRIBUIDORA DE FLORES LTDA - ME\"," +
" \"endereco\": \"EST RSC-453 (ROTA DO SOL) KM 93,8\"," +
" \"bairro\": \"BAIRRO ALFANDEGA\"," +
" \"numero\": 26," +
" \"complemento\": \"\"," +
" \"telefone\": \"3462 2749\"," +
" \"celular\": \"\"," +
" \"email\": \"giselaflores#giselaflores.com.br\"" +
" }" +
" ]" +
" }" +
"}";
try {
JSONObject jsonEmpresa = new JSONObject(JSONString);
String email = jsonEmpresa.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
2nd
try {
JSONObject jsonEmpresa = new JSONObject();
jsonEmpresa.put("cnpj", "05.743.645/0001-38");
jsonEmpresa.put("razao_social", "GISELA TRANSPORTES E DISTRIBUIDORA DE FLORES LTDA - ME");
jsonEmpresa.put("endereco", "EST RSC-453 (ROTA DO SOL) KM 93,8");
jsonEmpresa.put("bairro", "BAIRRO ALFANDEGA");
jsonEmpresa.put("numero", 26);
jsonEmpresa.put("complemento", "");
jsonEmpresa.put("telefone", "3462 2749");
jsonEmpresa.put("celular", "");
jsonEmpresa.put("email", "giselaflores#giselaflores.com.br");
String email = jsonEmpresa.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
String email's value is null, it should be giselaflores#giselaflores.com.br.
When I tried to debug, I had the message jsonEmpresa: "null".
To get email value for given example, you should to do like
String JSONString = "{" +
" \"retorno\": {" +
" \"empresas\": [" +
" {" +
" \"cnpj\": \"05.743.645/0001-38\"," +
" \"razao_social\": \"GISELA TRANSPORTES E DISTRIBUIDORA DE FLORES LTDA - ME\"," +
" \"endereco\": \"EST RSC-453 (ROTA DO SOL) KM 93,8\"," +
" \"bairro\": \"BAIRRO ALFANDEGA\"," +
" \"numero\": 26," +
" \"complemento\": \"\"," +
" \"telefone\": \"3462 2749\"," +
" \"celular\": \"\"," +
" \"email\": \"giselaflores#giselaflores.com.br\"" +
" }" +
" ]" +
" }" +
"}";
try {
JSONObject jsonEmpresa = new JSONObject(JSONString);
JSONObject retorno = jsonEmpresa.getJSONObject("retorno");
JSONArray empresas = retorno.getJSONArray("empresas");
JSONObject empresa = empresas.getJSONObject(0);
String email =empresa.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}

How to call methods (maybe recursive) itself JAVA

Hello I am new in Java and I have a question.
I am using a package to parse JSON Markups but the following problem is this:
{
"example": {
"subThing": "value"
},
"anotherThing" : 0
...
}
if I call MyClass.getString("example").getString("subThing"); then I am getting the value of subThing.
I want to call these getString() so often as possible ina for loop programmatically with index variable. But I don't know how to do.
for(int i = 0; i > getCurrentState(); i++) {
//Here I want to call getString();
//I want in round loop to call getString();
//In second round loop to call getString().getString();
}
Sorry I just started using java 1 week ago.
edit:
I mean how to call get() and/or getString() programmatically in for loop?
I'm not sure if I understand you correctly, but you may use the following technique here:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class App
{
public static void main( String[] args ) throws JSONException {
JSONObject newObj = new JSONObject("{" +
"\"data\": [\n" +
" {\n" +
"\"id\": 1,\n" +
" \"userId\": 1,\n" +
" \"name\": \"ABC\",\n" +
" \"modified\": \"2014-12-04\",\n" +
" \"created\": \"2014-12-04\",\n" +
" \"items\": [\n" +
" {\n" +
" \"email\": \"abc#gmail.com\",\n" +
" \"links\": [\n" +
" {\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"\n" +
"}");
JSONArray items = newObj.getJSONArray("data");
for (int it = 0; it < items.length(); it++) {
JSONObject contactItem = items.getJSONObject(it);
String userName = contactItem.getString("name");
JSONArray item = contactItem.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
String email = item.getJSONObject(i).getString("email");
System.out.println(email);
}
System.out.println("Name----------" + userName);
}
}
}
or even better and simpler is to use JsonPath
For your json is would be smth like this
String substring = JsonPath.parse(json).read("$.example.subThing", String.class);
String anotherstring = JsonPath.parse(json).read("$.anotherThing", String.class);

Losing focus on SwingX JCOMBO BOX

I want to achieve AutoSuggest ComboBox 2 problems I am facing
1st getting an array of id and name both want the name only.
Array i am receiving
2nd losing focus on typing the text.
Please help
database Query
public SentenceList getAutoProductList() {
return new StaticSentence(s, "SELECT "
+ "P.ID, "
+ "P.REFERENCE, "
+ "P.CODE, "
+ "P.CODETYPE, "
+ "P.NAME, "
+ "P.PRICEBUY, "
+ "P.PRICESELL, "
+ "P.CATEGORY, "
+ "P.TAXCAT, "
+ "P.ATTRIBUTESET_ID, "
+ "P.STOCKCOST, "
+ "P.STOCKVOLUME, "
+ "P.IMAGE, "
+ "P.ISCOM, "
+ "P.ISSCALE, "
+ "P.ISKITCHEN, "
+ "P.PRINTKB, "
+ "P.SENDSTATUS, "
+ "P.ISSERVICE, "
+ "P.ATTRIBUTES, "
+ "P.DISPLAY, "
+ "P.ISVPRICE, "
+ "P.ISVERPATRIB, "
+ "P.TEXTTIP, "
+ "P.WARRANTY, "
+ "P.STOCKUNITS "
+ "FROM PRODUCTS P "
+ "ORDER BY NAME", null, ProductInfoExt.getSerializerRead());
}
Auto Complete JcomboBox Code
SentenceList sentProductNames = dlSales.getAutoProductList();
m_JComboProductName.setEditable(true);
ComboBoxValModel m_jProductNameModel = new ComboBoxValModel();
editor = (JTextComponent) m_JComboProductName.getEditor().getEditorComponent();
List productList = null;
try {
productList = sentProductNames.list();
} catch (Exception e) {
}
productList.add(0, null);
m_jProductNameModel = new ComboBoxValModel(productList);
m_JComboProductName.setModel(m_jProductNameModel);
AutoCompleteDecorator.decorate(m_JComboProductName);
System.out.println("product List "+ productList);
if(m_JComboProductName.getItemCount()>0){
m_JComboProductName.setSelectedIndex(0);
}

Cycle for error

I have one problem with my cycle for.
I parse data with JsonParser and after i use one cycle for print all data but i recive only the last result.
This is the code:
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.d("id_Persons", "id: " + json_data.getString("id_Persons")
+ ", nome: " + json_data.getString("name")
+ json_data.getString("address")
);
stringaFinale = json_data.getString("id_Persons") + " "
+ json_data.getString("name") + " "
+ json_data.getString("address");
}
return stringaFinale;
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
but, with
Log.d("id_Persons", "id: " + json_data.getString("id_Persons")
+ ", nome: " + json_data.getString("name")
+ json_data.getString("address")
);
I do not understand what is the error.
This is the screen of app
You are overwriting its value in each iteration of for loop.
Change
stringaFinale = json_data.getString("id_Persons") + " " + json_data.getString("name") + " " + json_data.getString("address");
to
stringaFinale += json_data.getString("id_Persons") + " " + json_data.getString("name") + " " + json_data.getString("address");
Note: You should initialize stringaFinale with empty string like this
String stringaFinale = "";
Update: Another nicer way is to use StringBuilder like this
// declare it before the loop
StringBuilder stringaFinale = new StringBuilder(200); // use appropriate size
//Inside the loop
stringaFinale.append(json_data.getString("id_Persons") + " " + json_data.getString("name") + " " + json_data.getString("address"));
//Get the value
stringFinale.toString();

JSON String to POJO, using GSON, clarification needed

I have a JSON file, as String:
String compString = "{\n" +
" \"Component\": {\n" +
" \"name\": \"Application\",\n" +
" \"environment\": \"QA\",\n" +
" \"hosts\": [\n" +
" \"box1\",\n" +
" \"box2\"\n" +
" ],\n" +
" \"directories\": [\n" +
" \"/path/to/dir1/\",\n" +
" \"/path/to/dir2/\",\n" +
" \"/path/to/dir1/subdir/\",\n" +
" ]\n" +
" }\n" +
" }";
I have a bean representing it (correct if incorrectly)
public class Component {
String name;
String environment;
List<String> hosts = new ArrayList<String>();
List<String> directories = new ArrayList<String>();
// standard getters and setters
}
I am trying to feed this String to this class by:
Gson gson = new Gson();
Component component = gson.fromJson(compString, Component.class);
System.out.println(component.getName());
Above does not work. (I am getting null back, as if Component's name value is never set)
What am i missing please?
In fact, you have to remove the enclosing class from Json.
Indeed, JSON begins with the content of the enclosing class.
So your JSON would be:
String compString = "{\n" +
" \"name\": \"Application\",\n" +
" \"environment\": \"QA\",\n" +
" \"hosts\": [\n" +
" \"box1\",\n" +
" \"box2\"\n" +
" ],\n" +
" \"directories\": [\n" +
" \"/path/to/dir1/\",\n" +
" \"/path/to/dir2/\",\n" +
" \"/path/to/dir1/subdir/\",\n" +
" ]\n" +
" }\n";
String compString =
" {\n" +
" \"name\": \"Application\",\n" +
" \"environment\": \"QA\",\n" +
" \"hosts\": [\n" +
" \"box1\",\n" +
" \"box2\"\n" +
" ],\n" +
" \"directories\": [\n" +
" \"/path/to/dir1/\",\n" +
" \"/path/to/dir2/\",\n" +
" \"/path/to/dir1/subdir/\",\n" +
" ]}" ;
I think you should read more about json, I have removed something in your json string and then success.

Categories