Get Arraylist file json using java - 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 } ] }

Related

org.json.JSONException: JSONObject["properties"] not found

I am new to programming and am trying to read massages from Kafka as a whole String and convert them into a JSON object (Array) and then access each element in the JSON Array to extract the values. But it is giving me the following error:
org.json.JSONException: JSONObject["properties"] not found.
Here is my JSON Array:
Please note that I have multiple JSON arrays like this which is why I am looping them all to iterate this process and put them each in a separate JSON Object.
{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"STATIONS_ID": 662, "MESS_DATUM": 202204120000, "RWS_DAU_10": 0, "RWS_10": 0.0, "RWS_IND_10": 0}, "geometry": {"type": "Point", "coordinates": [10.516667, 52.266666]}}]}
This is my code:
// input massages from a Kafka topic
JSONObject json_obj = new JSONObject(valueFromKafka);
// Access to the JSON Array element "features"
JSONArray jsonFeatures = (JSONArray) objJsonObject.getJSONArray("features");
// for anhanced loop to iterate this process
for (Object feature_obj : jsonFeatures) {
JSONObject feature = new JSONObject(feature_obj);
// access and get values from the JSON Array
Long STATIONS_ID = feature.getJSONObject("properties").getLong("STATIONS_ID");
Long MESS_DATUM = feature.getJSONObject("properties").getLong("MESS_DATUM");
Double RWS_DAU_10 = feature.getJSONObject("properties").getDouble("RWS_DAU_10");
Long RWS_IND_10 = feature.getJSONObject("properties").getLong("RWS_IND_10");
Float RWS_10 = feature.getJSONObject("properties").getFloat("RWS_10");
JSONArray coordJson = feature.getJSONObject("properties").getJSONObject("geometry").getJSONArray("coordinates");
String pointWKT = "POINT(" + coordJson.getFloat(0) + " " + coordJson.getFloat(1) + ")";
Try the below code:
JSONObject json_obj = new JSONObject(valueFromKafka);
JSONArray features = json_obj.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
JSONObject feature = features.getJSONObject(i);
/*JSONObject properties = feature.getJSONObject("properties");*/
Long STATIONS_ID = feature.getJSONObject("properties").getLong("STATIONS_ID");
Long MESS_DATUM = feature.getJSONObject("properties").getLong("MESS_DATUM");
Double RWS_DAU_10 = feature.getJSONObject("properties").getDouble("RWS_DAU_10");
Long RWS_IND_10 = feature.getJSONObject("properties").getLong("RWS_IND_10");
Float RWS_10 = feature.getJSONObject("properties").getFloat("RWS_10");
JSONArray coordJson = feature.getJSONObject("geometry").getJSONArray("coordinates");
String pointWKT = "POINT(" + coordJson.getDouble(0) + " " + coordJson.getDouble(1) + ")";
}
try this(Use FastJson)
ValType target = JSON.jsonToObject(val, ValType.class);
and then u can continue to foreach this Collection

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

JSON array from JSON object is returning null

I want to read JSON array
"connectTo":[
{
"url": "wss://localhost/opt/siml"
}
],
from JSON string :
{
"cluster":{
"enabled":"true",
"clusterName":"cluster0",
"simlURL":"wss://localhost:5443/opt/siml"
},
"simlFieldWatchUrl":"fieldwatchholder.jsp",
"persistFolder":"clusterconfig/concentratorBPersist",
"sslCrtFile":"clusterconfig/certDirB/siml.crt",
"sslKeyFile":"clusterconfig/certDirB/siml.key",
"SIMLID":"TestServerB",
"localWebProxyServer":"localhost",
"localWebProxyPort":8080,
"SIMLProxyPort":8400,
"SIMLWebPort":8300,
"turnOnExtraSIMLWebSocket":"false",
"autoPromoteNewConnectionsFromPurgatory":true,
"connectTo":[
{
"url": "wss://localhost/opt/siml"
}
],
"tempLogins":[
{
"username":"root",
"password":"root"
}
]
}
My code to read url is:
JSONArray connectTo = (JSONArray) config.get("connectTo");
System.out.println("Connect to : " + connectTo);
for (Object o : connectTo) {
JSONObject connect = (JSONObject) o;
String url = (String) connect.get("url");
System.out.println(url);
}
But System.out.println("Connect to : " + connectTo); this is returning
Connect to : []
I read some old question but did not get satisfactory answer. Please Help. And thank you in advance :)
I just assume config is a JSONObject.
JSONArray connectTo = config.getJSONArray("connectTo");
config.get() returns an Object while config.getJSONArray() returns a JSONArray.
Try this:
JSONArray connectTo =config.getJSONArray("connectTo");
System.out.println("Connect to : " + connectTo);
for (int i=0;i<connectTo.length();i++)
{
JSONObject connect = connectTo.getJSONObject(i);
String url = connect.get("url");
System.out.println(url);
}
I got it working like this, not sure if this helps:
var json = {
"connectTo": [{
"url": "wss://localhost/opt/siml"
}]
};
for (var o = 0; o < json.connectTo.length; o++) {
console.log(json.connectTo[o].url);
}

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 parse a JSON string using ggson to get field values

I have a sample JSON as below. I need to get the individual fields like ASIdentifer and ExternalIdentifer. I have stored this JSON data in a string.
Using GoogleJson as the module(ggson)
JSON data:
{
"DeviceCommon": {
"ASIdentifier": "123",
"DatadeliveyMechanism": "notify",
"MobileOriginatorCallbackReference": {
"url": "http://application.example.com/inbound/notifications/modatanotification/"
},
"AccessiblityCallbackReference": {
"url": "http://application.example.com/inbound/notifications/accessibilitystatusnotification"
}
},
"DeviceList": [{
"ExternalIdentifer": "123456#mydomain.com",
"msisdn": "123456",
"senderName": "Device1",
"MobileOriginatorCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/modatanotification/"
},
"ConfigurationResultCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/configurationResult"
},
"ASreferenceID": "AS000001",
"NIDDduration": "1d"
}]
}
I created the POJO classes and parsed the data using below code
data = new Gson().fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), Data.class);
System.out.println(data);
Output:
Data{
deviceCommon=DeviceCommon{
asIdentifier='123'
datadeliveyMechanism='notify'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
accessiblityCallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification
}
deviceList=[DeviceListEntry{
externalIdentifer='123456#mydomain.com'
msisdn='123456'
senderName='Device1'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult
asReferenceID='AS000001'
nidDduration='1d'
}]
}
String jsonInString = gson.toJson(data);
System.out.println("String is"+ jsonInString);
Output:
String is{"DeviceCommon":{"ASIdentifier":"123","DatadeliveyMechanism":"notify","MobileOriginatorCallbackReference":{"url":"http://application.example.com/inbound/notifications/modatanotification/"},"AccessiblityCallbackReference":{"url":"http://application.example.com/inbound/notifications/accessibilitystatusnotification"}},"DeviceList":[{"ExternalIdentifer":"123456#mydomain.com","msisdn":"123456","senderName":"Device1","MobileOriginatorCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/modatanotification/"},"ConfigurationResultCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/configurationResult"},"ASreferenceID":"AS000001","NIDDduration":"1d"}]}
I need to parse this JSON string to get individual fields like ExternalIdentifier and ASIdentifier.
I tried something like this but it is not working.
JsonObject jobj = new Gson().fromJson(jsonInString, JsonObject.class);
String result = jobj.get("ASIdentifier").toString();
System.out.println("value is"+ result);
Note: ExternalIdentifier is within the array, so I need to loop through the array to find it.
Can you please tell me what I'm doing wrong?
Possible solution:
String result = jobj.get("DeviceCommon").getAsJsonObject().get("ASIdentifier").getAsString();
System.out.println("ASIdentifier: "+ result);
JsonArray jsonArray = jobj.get("DeviceList").getAsJsonArray();
for (JsonElement device : jsonArray ) {
result = device.getAsJsonObject().get("ExternalIdentifer").getAsString();
System.out.println("ExternalIdentifer: "+ result);
}
Output:
ASIdentifier: 123
ExternalIdentifer: 123456#mydomain.com
public static void printJson(JsonElement jsonElement,String key) {
// Check whether jsonElement is JsonObject or not
if (jsonElement.isJsonObject()) {
Set<Entry<String, JsonElement>> ens = ((JsonObject) jsonElement).entrySet();
if (ens != null) {
// Iterate JSON Elements with Key values
for (Entry<String, JsonElement> en : ens) {
// System.out.println("##key is"+en.getKey() + " : ");
printJson(en.getValue(), en.getKey());
// System.out.println(en.getValue().getAsString());
// System.out.println(jsonElement.getAsString());
}
}
}
// Check whether jsonElement is Primitive or not
else if (jsonElement.isJsonPrimitive()) {
// print value as String
System.out.println("###key is"+key);
System.out.println("### value is"+jsonElement.getAsString());
}
else if (jsonElement.isJsonArray()) {
JsonArray jarr = jsonElement.getAsJsonArray();
// Iterate JSON Array to JSON Elements
System.out.println("\n###Array size is"+ jarr.size());
for (JsonElement je : jarr) {
printJson(je,key);
}
}
}

Categories