How to parse JSON File to Object - java

I have below item, how to parse the nested object into java variable. I am using JSON document but not sure how to parse the sub object. Please see the JSON item and java code
JSON:
{
"_id" : "328",
"website" : "www.abc.com",
"addresses" : [
{
"addressType" : "PRIMARY",
"address" : "102 Yonge Street",
"city" : "Toronto",
"postalCode" : "M2N 6T6",
"state" : {
"code" : "ON",
"name" : "Ontario",
"countryCode" : "CA"
},
"country" : "Canada"
},
{
"addressType" : "SECONDARY",
"address" : "180 Yonge Street",
"city" : "Toronto",
"postalCode" : "L6P 6T7",
"state" : {
"code" : "ON",
"name" : "Ontario",
"countryCode" : "CA"
},
"country" : "Canada"
}
],
"phoneNumber" : "123456"
}
Java Code:
DynamicMappingFile objDynoMapping = new DynamicMappingFile();
ConfigReader objConfigReader = new ConfigReader();
public String strSQL(String strFullDocument)
{
String sqlInsertStatement = "";
System.out.println("Value of strFullDocument is " + strFullDocument);
String lstrInsertColumnStatement ="";
String charAfterColumnStatement = ")";
String lstrInsertValuesStatement ="values (";
String lstrColumnValues = "";
String lstrBSONDocValue = "";
String lstrColumnName;
int columnIndex = 0;
int documentLength = BsonDocument.parse(strFullDocument).size();
final BufferedReader br;
String lstrMySQLColumneName="";
String MySQLColumnNames = "";
String lstrMongoandMySQLDBFields="";
int lstrBSONDoubleValue = 0;
try {
br = new BufferedReader(new FileReader("./Configuration/MongoMySQLMapping.csv"));
lstrInsertColumnStatement = lstrInsertColumnStatement.concat("Insert into " + objConfigReader.mySQLTable + " (");
System.out.println("Value of Insert statement is : " + lstrInsertColumnStatement);
while(br.ready()){
lstrMongoandMySQLDBFields = br.readLine(); //Skip the header line
System.out.println(lstrMongoandMySQLDBFields);
objDynoMapping.add(objDynoMapping.new MapFields(lstrMongoandMySQLDBFields));
}
}
catch(Exception errBuff) {
System.out.println(errBuff.toString());
}
System.out.println("Length of Document is " + documentLength);
lstrColumnName = BsonDocument.parse(strFullDocument).keySet().toString().replace("[", "").replace("]", "");
System.out.println("value of lstrcolumnname");
Set<String> setKeys = BsonDocument.parse(strFullDocument).keySet();
Iterator<String> itr = setKeys.iterator();
System.out.println("Value of keys");
while(itr.hasNext())
{
System.out.println("Inside while");
String keys = (String) itr.next();
lstrMySQLColumneName = objDynoMapping.lsMapFields.get(keys).keySet().toString().replace("[", "").replace("]", "");
System.out.println("lstrMySQLColumneName" + lstrMySQLColumneName);
if(BsonDocument.parse(strFullDocument).get(keys).isObjectId())
{
System.out.println("Inside object id");
lstrBSONDocValue = (String)BsonDocument.parse(strFullDocument).get(keys).asObjectId().getValue().toString();
System.out.println("lstrBSONDocValue is" + lstrBSONDocValue);
}
else if(BsonDocument.parse(strFullDocument).get(keys).isString())
{
// details[i] = BsonDocument.parse(strFullDocument).get(keys).asString().getValue();
System.out.println("Inside else of string");
lstrBSONDocValue = (String)BsonDocument.parse(strFullDocument).get(keys).asString().getValue();
System.out.println("Value is " + lstrColumnValues);
// System.out.println("Value of details is " + details[i]);
}
else if(BsonDocument.parse(strFullDocument).get(keys).isInt32())
{
// details[i] = BsonDocument.parse(strFullDocument).get(keys).asString().getValue();
System.out.println("Inside int value");
lstrBSONDocValue = String.valueOf(BsonDocument.parse(strFullDocument).get(keys).asInt32().getValue());
System.out.println("Value is " + lstrBSONDoubleValue);
// System.out.println("Value of details is " + details[i]);
}
if(columnIndex!=documentLength-1)
{
System.out.println("insode column index");
MySQLColumnNames = MySQLColumnNames.concat(lstrMySQLColumneName + ",");
if(BsonDocument.parse(strFullDocument).get(keys).isObjectId())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat("\"" + lstrBSONDocValue + "\",");
System.out.println("After is " + lstrColumnValues);
}
if(BsonDocument.parse(strFullDocument).get(keys).isString())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat("\"" + lstrBSONDocValue + "\",");
System.out.println("After is " + lstrColumnValues);
}
if(BsonDocument.parse(strFullDocument).get(keys).isInt32())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat(String.valueOf(lstrBSONDocValue) + ",");
System.out.println("After is " + lstrColumnValues);
}
}
else
{
System.out.println("Insode else column");
MySQLColumnNames = MySQLColumnNames.concat(lstrMySQLColumneName);
if(BsonDocument.parse(strFullDocument).get(keys).isObjectId())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat("\"" + lstrBSONDocValue + "\",");
System.out.println("After is " + lstrColumnValues);
}
if(BsonDocument.parse(strFullDocument).get(keys).isString())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat("\"" + lstrBSONDocValue + "\"");
System.out.println("After is " + lstrColumnValues);
}
if(BsonDocument.parse(strFullDocument).get(keys).isInt32())
{
System.out.println("Before is " + lstrColumnValues);
lstrColumnValues = lstrColumnValues.concat(String.valueOf(lstrBSONDocValue));
System.out.println("After is " + lstrColumnValues);
}
//
// System.out.println("lstrColumnValues 1 is " + lstrColumnValues);
}
columnIndex++;
}
sqlInsertStatement = sqlInsertStatement.concat(lstrInsertColumnStatement + MySQLColumnNames + charAfterColumnStatement + lstrInsertValuesStatement + lstrColumnValues + ")");
System.out.println("Final Value of Insert is " + sqlInsertStatement);
return sqlInsertStatement;
}

Related

Get value from multiple checkbox's selected and display in TextArea

I will have display all the toppings the user selected and there can be more than one but my code only display one at a time. Please advise.
Here is my code for toppings part:
public String toppingsSelect()
{
String toppingsSelectString = "";
if(tomatoCheckBox.isSelected())
{
toppingsSelectString = "Tomato";
}
if(greenPeppersCheckBox.isSelected())
{
toppingsSelectString = "Green Peppers";
}
if(mushroomsCheckBox.isSelected())
{
toppingsSelectString = "Mushrooms";
}
if(blackOlivesCheckBox.isSelected())
{
toppingsSelectString = "Black Olives";
}
if(sausageCheckBox.isSelected())
{
toppingsSelectString = "Sausage";
}
if(extraCheeseCheckBox.isSelected())
{
toppingsSelectString = "Extra Cheese";
}
return toppingsSelectString;
}
displayString = "Pizza type : " + crustSelect() + "\n" +
"Pizza size : " + sizeSelect() + "\n" +
"Toppings : " + toppingsSelect() + "\n" +
"Amount Due : " + dollarDecimalFormat.format(totalPriceFloat);
outputTextArea.setText(displayString);
Each time you assign a value to toppingsSelectString it replace the precedent value. You should put for exemple toppingsSelectString += " " + "Tomato";

how to iterate json and convert into following json format in JAVA

How to iterate json in java. I wanted iterate elements inside payload, grab the first level and second level key and array value. I have converted the same in python. I'm new to java and wanted convert in java. Any help would be appreciated.
Python Code:
import os
import sys
import json
import datetime
def lambda_handler(event, context):
indata = event['payload']
outputDictionary = []
for i in indata:
for j in indata[i]:
for k in indata[i][j]:
outputDictionary.append(dict(source = i,code=j,version=k))
return outputDictionary
Input :
{
"payload": {
"gtl": {
"435185": [
"2019-11-27T14:34:32.368197Z"
]
},
"ptl": {
"A0947863": [
"2019-11-27T14:34:32.368197Z"
]
},
"mtl": {
"A0947863": [
"2019-11-27T14:34:32.368197Z",
"2021-04-27T06:13:12.841968Z"
]
}
}
}
Expected Output
[
{
"source": "gtl",
"code": "435185",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "ptl",
"code": "A0947863",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "mtl",
"code": "A0947863",
"version": "2019-11-27T14:34:32.368197Z"
},
{
"source": "mtl",
"code": "A0947863",
"version": "2021-04-27T06:13:12.841968Z"
}
]
SOLVED IN JAVA:
Java CODE:
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ParseJson {
public static void main(String[] args) {
String inputJson = "{\r\n" +
" \"payload\": {\r\n" +
" \"gtl\": {\r\n" +
" \"435185\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"ptl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"mtl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\",\r\n" +
" \"2021-04-27T06:13:12.841968Z\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
final JSONObject inputJSONOBject = new JSONObject(inputJson);
JSONObject jsonChildObject = (JSONObject)inputJSONOBject.get("payload");
Iterator iterator = jsonChildObject.keys();
while (iterator.hasNext()) {
String key = null;
while(iterator.hasNext()){
String source = (String)iterator.next();
JSONObject codeChildObject = jsonChildObject.getJSONObject(source);
Iterator iterator2 = codeChildObject.keys();
while(iterator2.hasNext()){
String code = (String)iterator2.next();
org.json.JSONArray jsonArray = codeChildObject.getJSONArray(code);
for(int i=0;i<jsonArray.length();i++){
System.out.println("Source:" + source);
System.out.println("CODE:" + code);
System.out.println("Version: "+jsonArray.get(i));
}
}
}
}
}
//System.out.println(inputJSONOBject);
}
You have done everything right except for that extra loop for the first iterator. Following is the complete working solution.
class ParseJson {
public static void main(String[] args) throws Exception {
String inputJson = "{\r\n" +
" \"payload\": {\r\n" +
" \"gtl\": {\r\n" +
" \"435185\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"ptl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\"\r\n" +
" ]\r\n" +
" },\r\n" +
" \"mtl\": {\r\n" +
" \"A0947863\": [\r\n" +
" \"2019-11-27T14:34:32.368197Z\",\r\n" +
" \"2021-04-27T06:13:12.841968Z\"\r\n" +
" ]\r\n" +
" }\r\n" +
" }\r\n" +
"}";
JSONArray output = convert(inputJson);
System.out.println(output.toString(5));
}
private static JSONArray convert(String inputJson) throws Exception {
final JSONObject inputJSONOBject = new JSONObject(inputJson);
JSONObject jsonChildObject = (JSONObject) inputJSONOBject.get("payload");
JSONArray outputArray = new JSONArray();
Iterator payloadIterator = jsonChildObject.keys();//gtl,ptl,mtl
while (payloadIterator.hasNext()) {
String source = (String) payloadIterator.next(); //gtl
JSONObject codeChildObject = jsonChildObject.getJSONObject(source);
Iterator codeIterator = codeChildObject.keys();//123, 456
while (codeIterator.hasNext()) {
String code = (String) codeIterator.next();//123
org.json.JSONArray jsonArray = codeChildObject.getJSONArray(code);// t1,t2,t3
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = new JSONObject();
object.put("source", source);
object.put("code", code);
object.put("version", jsonArray.get(i)); //t1
outputArray.put(object);
}
}
}
return outputArray;
}
}

why does the following keep returning an out of bounds error?

Please help my figure out why this keeps throwing an out of bounds error. i tried making a separate loop keep track of AdminDecisions
String returnProfile() {
String uniPicksString ="";
String studentInfo = null;
//for(int i = 0; i<ApplicantArray.size(); i++) {
studentInfo =FAMILYNAME+ ", " + "average = " + AVERAGE + " ";
for (int j = 0; j<CHOICES.size(); j++) {
if(j<CHOICES.size() - 1) {
uniPicksString = uniPicksString + CHOICES.get(j)+ ": " + " admin decision, " ;
}else {
uniPicksString = uniPicksString + CHOICES.get(j)+ ": " + " admin decision" + "\n";
}
}
//}
return studentInfo + uniPicksString + "\n";
}
the following code shows the desired out put but i cant return it as a string
String printProof() {
// System.out.println("from inside the student class");
String temp=null;
d = new ArrayList<String>();
for(int j = 0 ; j<1; j++) {
System.out.print("\n >>printProof<< " + FAMILYNAME+", " + "average = " + AVERAGE + " ");
for (int i = 0; i<AdminDecision.size(); i++) {
//System.out.println(AdminDecision.get(i));
//temp = CHOICES.get(i)+ ": " + AdminDecision.get(i) + ", ";
if(i<CHOICES.size() - 1) {
temp = CHOICES.get(i)+ ": " + AdminDecision.get(i) + ", ";
}else {
temp = CHOICES.get(i)+ ": " + AdminDecision.get(i) + "\n";
}
System.out.print(temp + " ");
d.add(AdminDecision.get(i));
}
}
return temp + "\n";
}

How to access a variable outside a loop?

I need to access 'sets' outside the first for loop. How can i do that?
I want to sort on the result but i am not bale to access the result 'sets' outside the for loop. if I sort it inside, I am not getting the sort result as expected.
static Set < String > generateReports() {
try {
String[] parts2;
String part2 = null;
String[] parts3;
String part3 = null;
// String sets = null;
for (i = 1; i < 3; i++) {
String line = null;
FileReader fileReader1 = new FileReader("C:/Projects/Wells Fargo IVR/TestFolder/" + (i) + ".log");
BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
while ((line = bufferedReader1.readLine()) != null) {
String string = line;
parts2 = string.split("-");
if (parts2.length > 4) {
part2 = parts2[4];
sids.put(part2, line);
// System.out.println(sids.get(part2));
}
// if(IVRLogFileMerge.getSid().contains(part2)){
if (testSet.contains(part2)) {
// System.out.println("This is file number" + (i)+ " " + line);
for (String current: testSet1) {
if (line.contains(current)) {
//System.out.println(line);
testSetFinal.add(line);
String string1 = line.replace(" ", " ");
String string2 = string1.replace("default task", "Thread");
parts3 = string2.split(" ");
sets = (parts3[1] + " " + parts3[6] + " " + parts3[8] + " ");
//System.out.print(parts3[1] + " " + parts3[6] + " " + parts3[8] + " ");
for (int j = 10; j < parts3.length; j++) {
//System.out.print(parts3[j] + " ");
// bufferWritter.write(parts3[j] + " ");
sets = sets.concat(parts3[j] + " ");
}
FileWriter fileWritter = new FileWriter("C:/Projects/Wells Fargo IVR/TestFolder/file.txt", true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(sets);
bufferWritter.newLine();
bufferWritter.close();
// System.out.println();
String[] str = new String[] {
sets
};
Arrays.sort(str);
for (String s: str) {
//System.out.println(i + " " + s);
}
}
}
}
//bufferedWriter.write("This is file number" + (i)+ " " + line);
//bufferedWriter.newLine();
}
bufferedReader1.close();
}
//System.out.println(testSetFinal);
You have String sets = null; commented out currently. Uncomment that, and switch it to
String sets = "";

Reading all new messages from my gmail using javamail

I have an application which contains a GUI, it is using Javamail. When i open this Jframe I have to see messages that are sent to my mail on a jTextArea.
The problem is when i wrote my code it only shows just the last message sent.
How do I display all new messages in my inbox?
This is my code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Properties props = new Properties();
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", "mymail#gmail.com");
props.put("mail.pop3.socketFactory", 995);
props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.port", 995);
Session session = Session.getDefaultInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mymail#gmail.com", "mypassword");
}
});
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com", "mymail#gmail.com", "mypaswword");
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.READ_ONLY);
Message[] msg = fldr.getMessages();
Address[] address;
for (int i = 0; i < msg.length; i++) {
jTextArea1.setText("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
fldr.close(true);
store.close();
} catch (Exception e) {
System.out.println(e);
}
You repeatedly set the text of the jTextArea1 to the same contents in your loop over messages here:
for (int i = 0; i < msg.length; i++) {
jTextArea1.setText("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
You should build a StringBuilder with all the messages and then set the contents of the jTextArea1
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < msg.length; i++) {
sb.append("SentDate : " + msg[i].getSentDate() + "\n" + "From : " + msg[i].getFrom()[0] + "\n" + "Subject : " + msg[i].getSubject() + "\n" + "Message : " + "\n" + msg[i].getContent().toString());
}
jTextArea1.setText(sb.toString());
You can then make this a lot more legible by using an enhanced for loop and using the append method of the StringBuilder.
final StringBuilder sb = new StringBuilder();
for (Message message : msg) {
sb.append("SentDate : ").
append(message.getSentDate()).
append("\n").
append("From : ").
append(message.getFrom()[0]).
append("\n").append("Subject : ").
append(message.getSubject()).
append("\n").
append("Message : ").
append("\n").
append(message.getContent().toString());
}
jTextArea1.setText(sb.toString());
final StringBuilder sb = new StringBuilder();
for (Message message : msg) {
sb.append("SentDate : ").
append(message.getSentDate()).
append("\n").
append("From : ").
append(message.getFrom()[0]).
append("\n").append("Subject : ").
append(message.getSubject()).
append("\n").
append("Message : ").
append("\n").
append(message.getContent().toString());
}
jTextArea1.setText(sb.toString());

Categories

Resources