json SELECT multiple value by key in java - java

I have one json like below given
[{
"D_Table_Name": "BUILDING",
"S_Table_Name": "View1",
"S_Data_Field_Name": "USECD",
"D_Field_Name": "Description",
"MappingCode": "FIELD"
},
{
"D_Table_Name": "BUILDING",
"S_Table_Name": "View1",
"S_Data_Field_Name": "USECD",
"D_Field_Name": "StndCode",
"MappingCode": "FIELD"
},
{
"D_Table_Name": "asdasd",
"S_Table_Name": "View1",
"S_Data_Field_Name": "qwew",
"D_Field_Name": "ijhbgr4",
"MappingCode": "FIELD"
},
{
"D_Table_Name": "qwsdcv",
"S_Table_Name": "View1",
"S_Data_Field_Name": "kjmnbv",
"D_Field_Name": "dszfs",
"MappingCode": "FIELD"
}]
how to get all value of the key S_Table_Name

Assuming you are using any particular library to convert JSON string into an Object, Let's say I am taking GSON library
List<String> sTableNameValues = new ArrayList<>();
List<Map<String,String>> input = new GSON.fromJSON(inputJSONString);
for(Map.Entry<String,String> entry: input.entrySet()){
if(entry.getKey().equals("S_Table_Name")){
sTableNameValues.add(entry.getValue());
}
}
// Now all your S_Table_Name values are inside your list.

Use jackson library:
ObjectMapper mapper = new ObjectMapper();
JsonNode array = mapper.readValue(yourJson, JsonNode.class);
Get values:
for (int i = 0; i < array.size(); i++) {
String reportKey = array.get(i).get("S_Table_Name").textValue();
System.out.println(reportKey);
}

Something like json-path should be of help. In your case, the expression should be something like:
$[*].S_Table_Name

You can also use org.json.JSONObject library. Please see below code for this :
String response = "[{\"D_Table_Name\": \"BUILDING\",\"S_Table_Name\": \"View1\",\"S_Data_Field_Name\": \"USECD\",\"D_Field_Name\": \"Description\",\"MappingCode\": \"FIELD\"},{\"D_Table_Name\": \"BUILDING\",\"S_Table_Name\": \"View1\",\"S_Data_Field_Name\": \"USECD\",\"D_Field_Name\": \"StndCode\",\"MappingCode\": \"FIELD\"},{\"D_Table_Name\": \"asdasd\",\t\t\"S_Table_Name\": \"View1\",\"S_Data_Field_Name\": \"qwew\",\"D_Field_Name\": \"ijhbgr4\",\"MappingCode\": \"FIELD\"},{\"D_Table_Name\": \"qwsdcv\",\"S_Table_Name\": \"View1\",\t\"S_Data_Field_Name\": \"kjmnbv\",\"D_Field_Name\": \"dszfs\",\"MappingCode\": \"FIELD\"}]";
JSONArray responseArray = new JSONArray(response);
if (responseArray.length() > 0) {
for (int i = 0; i < responseArray.length(); i++) {
JSONObject responseObject = responseArray.getJSONObject(i);
if (responseObject.has("S_Table_Name")) {
String S_Table_Name = responseObject.getString("S_Table_Name");
System.out.println(S_Table_Name);
}
}
}

Related

Parse only particular fields in JSON at once

I have a huge JSON but I only need to parse specific fields. I know paths to these fields so I decided to try JPath and it works but I want to parse all fields at once.
Let's say I have such JSON:
{
"data": [
{
"field1": 1,
"field2": 1,
...
"another_data": [ {
"required_field1": "1",
"required_field2": "2"
}
],
...
}
]
}
I want to get only required fields with these paths and map it to Java POJO:
$.data[*].another_data[*].required_field1
$.data[*].another_data[*].required_field2
So as a final result I want to have a list of Java objects, where the object contains required_field1 and required_field2.
UPD:
how it works now
I have a Java POJO that's a container
class RequiredInfo {
private String field1;
private String field2;
//constructor, setters, etc
}
I read JSON path 2 times by using JPath:
String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
List<String> reqFields1 = JsonPath.read(document, "$.data[*].another_data[*].required_field1");
List<String> reqFields2 = JsonPath.read(document, "$.data[*].another_data[*].required_field2")
and then I map it to my POJO
for (int i = 0; i < reqFields1.size(); i++) {
res.add(new RequiredInfo(reqFields1.get(i), reqFields2.get(i)));
}
bit I think there is a better way how I can do it
You can try by creating a JSON object and get data:
JSONObject yourJsonObject = (JSONObject) new JSONParser().parse(yourJson);
JSONObject data = (JSONObject) yourJsonObject.get("data");
JSONObject data0 = (JSONObject) data.get(0);
JSONObject another_data = (JSONObject) data0.get("another_data");
String required_field1 = another_data.get("required_field1").toString();
String required_field2 = another_data.get("required_field2").toString();
Now that you have values, you can add them in your POJOs.

apply condition on json object with in json array java

I am fetching some json from server like this
"applications": [
{
"packageName": "com.facebook.mlite",
"defaultPermissionPolicy": "PROMPT",
"delegatedScopes": [
"DELEGATED_SCOPE_UNSPECIFIED",
"CERT_INSTALL",
"MANAGED_CONFIGURATIONS",
"BLOCK_UNINSTALL",
"PERMISSION_GRANT",
"PACKAGE_ACCESS",
"ENABLE_SYSTEM_APP"
],
"permissionGrants": [
{
"permission": "tt",
"policy": "PROMPT"
}
],
"disabled": false,
"minimumVersionCode": 0
},
{
"packageName": "com.facebook.mlite",
"defaultPermissionPolicy": "PROMPT",
"delegatedScopes": [
"DELEGATED_SCOPE_UNSPECIFIED",
"CERT_INSTALL",
"MANAGED_CONFIGURATIONS",
"BLOCK_UNINSTALL",
"PERMISSION_GRANT",
"PACKAGE_ACCESS",
"ENABLE_SYSTEM_APP"
],
"permissionGrants": [
{
"permission": "tt",
}
],
}
]
Now there is a json array "application":[] in which there are several json object. Now these object are not same. Some json objects are missing like first object contains installType but second one doesn't. Now i want to add this in a list for a recyclerview if a json object is missing i want to send empty tring in contrustor of my pojo class
public Application(String defaultPermissionPolicy, List<String> delegatedScopes, List<com.ariaware.enrolldevice.PolicyPojos.PermissionGrants> permissionGrants, Boolean disabled, String installType, Integer minimumVersionCode, String packageName) {
this.defaultPermissionPolicy = defaultPermissionPolicy;
this.delegatedScopes = delegatedScopes;
PermissionGrants = permissionGrants;
this.disabled = disabled;
this.installType = installType;
this.minimumVersionCode = minimumVersionCode;
this.packageName = packageName;
}
This is constructor of my class. Now how will i loop through json array and check either if an object exists or not or if doesn't exist then send empty string. I need to check every object
You could implement another constructor which accepts a JSONObject as a parameter and create the object. Inside the constructor use optString which returns an empty string if the field doesn't exist (also accepts another parameter for the fallback value).
public Application(JSONObject jsonObject) {
this.installType = jsonObject.optString("installType");
// example of an array
JSONArray scopes = jsonObject.optJSONArray("delegatedScopes");
this.delegatedScopes = new ArrayList<>();
for (int i = 0; i < scopes.length(); i++)
this.delegatedScopes.add(scopes.optString(i));
//other initialization...
}
Finally, you retrieve each JSONObject from the applications array.
try {
JSONArray res = data.optJSONArray("applications");
Application[] items = new Application[res.length()];
for (int i = 0; i < res.length(); i++)
items[i] = new Application(res.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}

Get Arraylist file json using java

I have problems with my code, I need to extract the "materias" markup in the arraylist. Example data:
[{
"name": "A114",
"grupo": "DAW2",
"tutor": 15,
"materias": ["DWES", "DWEC", "IW", "DAW", "IE"]
}]
I tried this, work but i need the content of the arraylist:
try { // this read the JSON file
line = new String(Files.readAllBytes(Paths.get("fileAulas")));
} catch (Exception ex) {
ex.printStackTrace();
}
JSONArray recs = new JSONArray(line);
for (Object rec : recs) {
Aula datos = new Aula();
JSONObject obj = ((JSONObject) rec);
String name = obj.getString("name");
//datos.setNombre(name);
String grupo = obj.getString("grupo");
//datos.setGrupo(grupo);
int tutor = obj.getInt("tutor");
//datos.setTutor(tutor);
}
My objetive is to read the arraylist and then datos.setArraylist to my another class. All works fine except read the arraylist
PD: I use java downloaded from Maven, to execute i use "javac -cp ./*: program.java"
materias is also an array, so you need something like:
JSONArray materias = obj.getJsonArray("materias");
List<String> materiasList = materias.getValuesAs(String.class);
This is not type-safe so you need to make sure the array will only have String values.
Also, if you are using Java 8, you can iterate over the values and store them manually (JsonArray is also a Collection<JsonValue>)
Quickly created short test implementation of your needs:
String json = "[{ \"name\":\"A114\",\"grupo\": \"DAW2\",\"tutor\":15,\"materias\": [\"DWES\",\"DWEC\",\"IW\",\"DAW\",\"IE\"]}]";
JSONArray objectArray = new JSONArray(json);
for (int x = 0; x < objectArray.length(); x++) {
JSONObject obj = objectArray.getJSONObject(x);
System.out.println("Name: " + obj.get("name"));
System.out.println("Grupo: " + obj.get("grupo"));
System.out.println("Tutor: " + obj.get("tutor"));
JSONArray materias = obj.getJSONArray("materias");
for (int y = 0; y < materias.length(); y++) {
System.out.println("Materia " + y + ": " + materias.get(y));
}
}
Output
Name: A114
Grupo: DAW2
Tutor: 15
Materia 0: DWES
Materia 1: DWEC
Materia 2: IW
Materia 3: DAW
Materia 4: IE
First gotta make your JSON Valid.
[{
"name": "A114",
"grupo": "DAW2",
"tutor": 15,
"materias": ["DWES", "DWEC", "IW", "DAW", "IE"]
}]
Secondly, you can try the following :
for (JsonElement rec : recs) {
Aula datos = new Aula();
JSONObject obj = rec.getAsJsonObject();
String name = obj.get("name").getAsString();
//datos.setNombre(name);
String grupo = obj.get("grupo").getAsString();
//datos.setGrupo(grupo);
int tutor = obj.get("tutor").getAsInt();
JsonObject obj = rec.getAsJsonObject();
JsonArray materias = obj.getAsJsonArray("materias");
List<String> materiasList = new ArrayList<>();
for (JsonElement item:
materias) {
materiasList.add(item.getAsString());
}
}
I believe that the syntax for an array in json is different that what you have in your file. For example - a simple complete json that contains an array of simple elements would be:
{"contacts":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Jen", "lastName":"Smith" },
{ "firstName":"David", "lastName":"Jones" }
]}
In your text, you specify an array, without the opening and closing JSON '{' and '}'. Also, You would need to name the array element ("contacts" in the example above). I think that what you want would be (I used "arrayName" for the array element name):
{"arrayName":[{ "name":"A114","grupo": "DAW2","tutor":15,"materias":["DWES","DWEC","IW","DAW","IE"] },
{ "name":"121","grupo": "DAW1","tutor":8,"materias":["PROGRA","BD","SIS","LM","FOL"] },
{ "name":"A112","grupo": "AUTO1","tutor":5 },
{ "name":"A127","grupo": "ASIR1","tutor":2 },
{ "name":"A114","grupo": "SMR2","tutor":11 },
{ "name":"A128","grupo": "ASIR2","tutor":9,"materias":["IAW","ABD","ASIS","SI","IE"] },
{ "name":"A125","grupo": "ADM2","tutor":12 } ] }

Extract json subset with few attributes from the main json

Is there an API/tool available for extracting specific attributes(json subset) of a json in java, similar to apache-commons beanutils copy?
For example I have the following JSON
{
"fixed":[
{
"b":"some value",
"c":"some value",
"d":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"c":"value",
"d":"value",
"e":"value",
"f":"value"
}
]
}
I would like to have the following json
{
"fixed":[
{
"b":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"e":"value",
"f":"value"
}
]
}
I came up the following method, but not sure if its the right approach
public JSONObject parseJSON(JSONObject data,List<String> subset){
JSONArray fixedArray = (JSONArray) data.get("fixed");
JSONObject resObj = new JSONObject();
JSONArray resArray = new JSONArray();
for(int i=0;i<fixedArray.size();i++){
JSONObject element = (JSONObject) fixedArray.get(i);
JSONObject resElement = new JSONObject();
for(String s:subset){
resElement.put(s, element.get(s));
}
resArray.add(resElement);
}
return resObj.put("fixed", resArray);
}
I had a look at this SO question, but wasn't helpful for this topic.
https://docs.oracle.com/javase/tutorial/jaxb/intro/arch.html you can also create you own pojo class from JAXB ,if you want.

Getting JSONObject from JSONArray [duplicate]

This question already has answers here:
Accessing members of items in a JSONArray with Java
(6 answers)
Closed 6 years ago.
I am in a bit of a fix regarding the JSONObject that I am getting as a response from the server.
jsonObj = new JSONObject(resultString);
JSONObject sync_reponse = jsonObj.getJSONObject("syncresponse");
String synckey_string = sync_reponse.getString("synckey");
JSONArray createdtrs_array = sync_reponse.getJSONArray("createdtrs");
JSONArray modtrs_array = sync_reponse.getJSONArray("modtrs");
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
String deleted_string = deletedtrs_array.toString();
{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]
as you can see in the response that I am getting I am parsing the JSONObject and creating syncresponse, synckey as a JSON object createdtrs, modtrs, deletedtrs as a JSONArray. I want to access the JSONObject from deletedtrs, so that I can split them apart and use the values. i.e I want to extract companyid, username, date etc.
How can I go about this ?
Thanks for your input.
JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:
JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// do some stuff....
}
Here is your json:
{
"syncresponse": {
"synckey": "2011-09-30 14:52:00",
"createdtrs": [
],
"modtrs": [
],
"deletedtrs": [
{
"companyid": "UTB17",
"username": "DA",
"date": "2011-09-26",
"reportid": "31341"
}
]
}
}
and it's parsing:
JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
JSONObject object3 = jArray3.getJSONObject(i);
String comp_id = object3.getString("companyid");
String username = object3.getString("username");
String date = object3.getString("date");
String report_id = object3.getString("reportid");
}
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
for(int i = 0; deletedtrs_array.length(); i++){
JSONObject myObj = deletedtrs_array.getJSONObject(i);
}
{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]
The get companyid, username, date;
jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date
start from
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array member
Iterating
for(int i = 0; i < deletedtrs_array.length(); i++){
JSONObject obj = deletedtrs_array.getJSONObject(i);
Log.d("Item no."+i, obj.toString());
// create object of type DeletedTrsWrapper like this
DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);
// String company_id = obj.getString("companyid");
// String username = obj.getString("username");
// String date = obj.getString("date");
// int report_id = obj.getInt("reportid");
}
Own object type
class DeletedTrsWrapper {
public String company_id;
public String username;
public String date;
public int report_id;
public DeletedTrsWrapper(JSONObject obj){
company_id = obj.getString("companyid");
username = obj.getString("username");
date = obj.getString("date");
report_id = obj.getInt("reportid");
}
}
When using google gson library.
var getRowData =
[{
"dayOfWeek": "Sun",
"date": "11-Mar-2012",
"los": "1",
"specialEvent": "",
"lrv": "0"
},
{
"dayOfWeek": "Mon",
"date": "",
"los": "2",
"specialEvent": "",
"lrv": "0.16"
}];
JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
JsonArray jsonArray = root.getAsJsonArray();
JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject();
String dayOfWeek = jsonObject1.get("dayOfWeek").toString();
// when using jackson library
JsonFactory f = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
JsonParser jp = f.createJsonParser(getRowData);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT) {
Map<String,Object> userData = mapper.readValue(jp, Map.class);
userData.get("dayOfWeek");
// process
// after binding, stream points to closing END_OBJECT
}
Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .operator like normal JAVA Object. It makes response handling very simple.

Categories