Parsing Json objects inside objects using Gson and get the length - java

I have a json file like below and want to parse the overlays like overlay1,overlay2,overlay3:
{
"overlays": {
 "overlay1": {
"imagesFPS": 12,
"clickThrough": false,
"repeatCount": 0,
  "sensitivity": 0.6,
},
"overlay2": {
"cgButtonPressedColor": "#ffaa56",
 "relative": "screen",
  "isOverlayRendered": true,
  "cgBorderWidth": "0px",
},
"overlay3": {
"cgButtonPressedColor": "#007f00",
"text": "Goto Page3 on Touch 5 Release",
}
}
}
Currently I am doing this:
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonObject ovl = job.getAsJsonObject("overlays");
for (int i = 1; i <= 100; i++) {
JsonObject overlay = ovl.getAsJsonObject("overlay" + i);
if (overlay != null) {
osb.setOverlay(jsp.getOverlay(overlay));
}
}
How can I get the length of overlays (here: overlay1, overlay2, overlay3)? How do I query the length of 3 via the gson API?
And I want to know the overlay1,overlay2,overlay3 in a string or array so that I can iterate over them.
Note: Here I have to iterate 100 times or any times so that I can iterate if overlays increase later in json file. It iterates unnecessarily in looping.
How can I iterate only overlay1 or overlay2 or overlay3 and so without unnecessary iterating?
I mean I just want to get the overlay1, overlay2, overlay3 and so on in jsonobjects via Gson.

I have solved this using this code below.
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonObject ovl = job.getAsJsonObject("overlays");
Map<String, Object> data = new Gson().fromJson(ovl, type);
Iterator<String> entries = data.keySet().iterator();
while (entries.hasNext())
{ JsonObject overlay = ovl.getAsJsonObject(entries.next().toString());
if (overlay != null)
{
osb.setOverlay(jsp.getOverlay(overlay));
}
}

Have you considered using an array instead of wrapped objects?
{
"overlays": [
{"overlay1": {
"imagesFPS": 12,
"clickThrough": false,
"repeatCount": 0,
"sensitivity": 0.6,
}},
{"overlay2": {
"cgButtonPressedColor": "#ffaa56",
"relative": "screen",
"isOverlayRendered": true,
"cgBorderWidth": "0px",
}},
{"overlay3": {
"cgButtonPressedColor": "#007f00",
"text": "Goto Page3 on Touch 5 Release",
}}
]
}
And using this code:
Gson gson = new Gson();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonArray ovl = job.getAsJsonArray("overlays");
if (ovl != null) {
osb.setOverlay(jsb.getOverlay(ovl.get(ovl.lenght() - 1)));
}
Or if you want to use wrapped json objects, you should create a list and insert elements like this:
Gson gson = new Gson();
List<JsonObject> overlays = new LinkedList<>();
JsonObject job = gson.fromJson(fileReader, JsonObject.class);
JsonObject ovl = job.getAsJsonObject("overlays");
for (int i = 1; ; ++i) {
JsonObject overlay = ovl.getAsJsonObject("overlay" + i);
if (overlay == null) {
break;
} else {
overlays.put(overlay);
}
}
// Use "overlays" list

Related

How to export a nested JSONArray to CSV?

I have a JSONArray which contains multiple JSONObjects
[
{
"record":[
{
"timeStamp":"2018-10-11T05:36:51+00:00",
"code":200,
"text":"OK"
},
{
"hostname":"qwe",
"address":"192.168.1.1",
"type":"A",
"priority":"0",
"ttl":"3600"
},
{
"hostname":"www",
"address":"test.com",
"type":"CNAME",
"priority":"0",
"ttl":"3600"
}
]
},
{
"record":[
{
"timeStamp":"2018-10-11T05:36:52+00:00",
"code":200,
"text":"OK"
},
{
"hostname":"rty",
"address":"192.168.1.2",
"type":"A",
"priority":"0",
"ttl":"300"
},
{
"hostname":"*",
"address":"test",
"type":"CNAME",
"priority":"0",
"ttl":"3600"
}
]
}
]
How can I parse this JSONArray and export it as a CSV File.
This is what I have tried so far
File file=new File("/home/administrator/Desktop/test.csv");
String csv = jsonArray;
FileUtils.writeStringToFile(file, csv);
System.out.println("CSV created.");
My desired output is
timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl
2018-10-11T05:36:51+00:00,200,OK,qwe,192.168.1.1,A,0,300,www,test.com,CNAME,0,3600
2018-10-11T05:36:52+00:00,200,OK,rty,192.168.1.2,A,0,300,*,test,CNAME,0,3600
Is it possible to have an output like this given the JSONArray above?
Sorry for the late respond was bashing my keyboard for the past 30 minutes but I finally got it done, here is the code.
public static String getCSVData() throws IOException, JSONException {
Path jsonFile = Paths.get("json");
String json = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8);
JSONArray jsonArray = new JSONArray(json.trim());
List<List<String>> jsonArrays = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
List<String> jsonObjects = new ArrayList<>();
JSONArray record = jsonArray.getJSONObject(i).getJSONArray("record");
for (int i2 = 0; i2 < record.length(); i2++) {
JSONObject jsonObject = record.getJSONObject(i2);
if (i2 == 0) {
jsonObjects.add(jsonObject.get("timeStamp").toString());
jsonObjects.add(jsonObject.get("code").toString());
jsonObjects.add(jsonObject.get("text").toString());
} else {
jsonObjects.add(jsonObject.get("hostname").toString());
jsonObjects.add(jsonObject.get("address").toString());
jsonObjects.add(jsonObject.get("type").toString());
jsonObjects.add(jsonObject.get("priority").toString());
jsonObjects.add(jsonObject.get("ttl").toString());
}
}
jsonArrays.add(jsonObjects);
}
StringBuilder stringBuilder = new StringBuilder("timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl\n");
for(List<String> arrays : jsonArrays){
stringBuilder.append(StringUtils.join(arrays, ",")).append("\n");
}
return stringBuilder.toString().trim();
}
To explain the code first I looped over the first Array and then get the jsonObject of the first JSONArray and then get the jsonArray named "record" from the JsonObject I have gotten by looping over the first JSONArray and then loop over record and get all the items and save them into an ArrayList. and join them via StringUtils which is provided by JDK.
if you want to write it to file use this
Files.write(Paths.get("YOUR CSV FILE"), getCSVData().getBytes(StandardCharsets.UTF_8));
all the code I used are provided by JDK and org.json.
after we print out getCSVDate(); the output is:
timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl
2018-10-11T05:36:51+00:00,200,OK,qwe,192.168.1.1,A,0,3600,www,test.com,CNAME,0,3600
2018-10-11T05:36:52+00:00,200,OK,rty,192.168.1.2,A,0,300,*,test,CNAME,0,3600

Write a Json file in Java , nested objects instead of String

I have to read a sample pom file and write all technology and version in to json file, Im able to get the output in this format:
["{ name:junit ,Version:4.12}","{ name:spring-batch-test ,Version:3.0}","{ name:spring-boot-starter }","{ name:slf4j-api }"]
However I want to get output in this format:
[{ "name":"junit" ,"Version":"4.12"},{" name":"spring-batch-test" ,"Version":"3.0"},{"name":"spring-boot-starter" }]
My code :
Map<String, String> dependencies = Maps.newHashMap();
dependencies = populateProjectDepedencies(dependencies, pomFile);
In populateProjectDependencies
for (Dependency dependency : dependencyList) {
String version = "0.0";
if (dependency.getVersion() != null &&
dependency.getVersion().startsWith("${"))
{
version = (String) properties.get(dependency.getVersion()
.substring(2, dependency.getVersion().length() - 1));
} else {
version = dependency.getVersion();
}
if (version != null) {
String a1[]=version.split("\\.");
int i=a1.length;
if(i>=2)
{
version=a1[0]+"."+a1[1];
}
dependencies.put("{name:"+dependency.getArtifactId(),",
Version:"+version+"}" );
JSONArray jsonArray = prepareJsonObject(dependencies);
genarateTechnologyRadarJson(jsonArray);
writer.write(jsonArray.toJSONString());
As I understand from your question, you are holding json as String array but you want to hold data as JSONObject array. So,
JSONArray ja = new JSONArray();
for (Dependency dependency : dependencyList) {
.....
JSONObject obj=new JSONObject();
obj.put("name",dependency.getArtifactId());
obj.put("Version",version);
ja.put(obj);
//remove dependencies.put,JSONArray. and genarateTechnologyRadarJson(jsonArray);
}
writer.write(ja.toString());
UPDATE
This should be your complete code
JSONArray jsonArray = new JSONArray();
for (Dependency dependency: dependencyList) {
String version = "0.0";
if (dependency.getVersion() != null &&
dependency.getVersion().startsWith("${")) {
version = (String) properties.get(dependency.getVersion()
.substring(2, dependency.getVersion().length() - 1));
} else {
version = dependency.getVersion();
}
if (version != null) {
String a1[] = version.split("\\.");
int i = a1.length;
if (i >= 2) {
version = a1[0] + "." + a1[1];
}
}
JSONObject obj=new JSONObject();
obj.put("name",dependency.getArtifactId());
obj.put("Version",version);
jsonArray.put(obj);
}
writer.write(jsonArray.toJSONString());
Because, you are adding the value as a String
"{ name:"+dependency.getArtifactId(),"
Even, I'm not sure why are you manually constructing the JSON instead just pass the Map object to JSONObject.
JSONObject obj=new JSONObject(yourmap);

json SELECT multiple value by key in 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);
}
}
}

How to get dynamically changed Key's value in Json String using java

I'm trying to parse Json string using java, I have stuck up with some scenario.
See below is my JSON String:
"NetworkSettings": {
"Ports": {
"8080/tcp": [ // It will change dynamically like ("8125/udp" and "8080/udp" etc....)
{
"HostIp": "0.0.0.0",
"HostPort": "8080"
}
]
}
}
I try to parse the above json string by using the following code:
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
if(ntw_Ports_obj.has("8080/tcp"))
{
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
JsonObject ntwtcp_obj=arr_ntwtcp.get(0).getAsJsonObject();
if(ntwtcp_obj.has("HostIp"))
{
ntw_HostIp=ntwtcp_obj.get("HostIp").toString();
System.out.println("Network HostIp = "+ntw_HostIp);
}
if(ntwtcp_obj.has("HostPort"))
{
ntw_HostPort=ntwtcp_obj.get("HostPort").toString();
System.out.println("Network HostPort = "+ntw_HostPort);
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
In my code I have used this code
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
to get the value of "8080/tcp"
How can I get the values of dynamically changing key like ("8125/udp","8134/udp", etc...)
Note: I'm using gson library for parsing
After modification
public static void main(String args[])
{
try
{
JsonParser parser = new JsonParser();
JsonObject obj=(JsonObject)parser.parse(new FileReader("sampleJson.txt"));
System.out.println("obj = "+obj);
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
System.out.println("ntw_Ports_obj = "+ntw_Ports_obj);
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
System.out.println(keyObjects instanceof Map); //**** here the statement prints false
if (keyObjects instanceof Map) // *** so controls doesn't enters into the if() condition block *** //
{
Map map = (Map) keyObjects;
System.out.println("Map = "+map);
keys.addAll(map.keySet());
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println("Array List = "+jArray);
}
}
}
catch(Exception e)
{
}
}
You can do something like that (not tested but should be ok) :
if (ntw_Ports_obj.isJsonArray()) {
Iterator it = ntw_Ports_obj.getAsJsonArray().iterator();
while (it.hasNext()) {
JsonElement element = (JsonElement) it.next();
if(element.isJsonArray()){
JsonArray currentArray = element.getAsJsonArray();
// Do something with the new JsonArray...
}
}
}
So your problem is the key 8080/tcp is not fixed and it may change. when this situation you can try like this to get the value of the Dynamic key.
Set<Map.Entry<String, JsonElement>> entrySet = ntw_Ports_obj
.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}
Edit:
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
/** for the given json there is a one json object within the 'Ports' so the 'keyObjects' will be the 'Map'**/
if (keyObjects instanceof Map) {
Map map = (Map) keyObjects;
keys.addAll(map.keySet());
/**
* keys is a List it may contain more than 1 value, but for the given
* json it will contain only one value
**/
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}

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