Reading first json with this name TestNameUS.json from the amazon S3Client directory and getting the sql from it and then hitting the db using the sql and matching the result with other Amazon S3 output directory containing the TestNameUS.csv with the same name as the name of the first json.
My code is below. It gives me the sql.How to read the directory dynamically with the name
public class ReadJsonFile {
public static void main(String[] args) {
// TODO Auto-generated method stub
JSONParser jsonParser = new JSONParser();
try {
Object obj = jsonParser.parse(new FileReader("./TestNameUS.json"));
// A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
JSONObject jsonObject = (JSONObject) obj;
JSONArray query = (JSONArray) jsonObject.get("query");
String query1=null;
for(Object str : query) {
query1=(String)str;
}
System.out.println(query1);
System.out.println(query1.replaceAll("^\\('|\\'\\)$", ""));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I'm trying to parse a JSON File. I wrote the code below to parse using Java JSONParser:
public static void parseJSONResponse(JSONObject jsonObj) {
for (Object keyObj : jsonObj.keySet()) {
String key = (String) keyObj;
Object valObj = jsonObj.get(key);
if (valObj instanceof JSONObject) {
parseJSONResponse((JSONObject) valObj);
} else if (valObj instanceof JSONArray) {
System.err.println("ARRAY");
} else {
System.out.println(key + " -> " + valObj.toString());
}
}
}
public static void main(String[] args) {
try {
FileReader reader = new FileReader("C:\\Users\\extract.json");
JSONParser parser = new JSONParser();
Object obj = (JSONObject) parser.parse(reader);
JSONObject object = (JSONObject) (obj);
parseJSONResponse(object);
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
It returns me a response like this:
description -> For testing purposes only
indexUpdatedAt -> 1420751985
flags -> ["default","restorable","restorePossibleForType"]
data -> [["row-mfpy.gr8q.cpii","00000000-0000"],["00009","9BCA"]]
columns -> [{"renderTypeName":"meta_data","fieldName":":sid"},{"renderTypeName":"meta_data"}]
I need to further parse "flags", "data" & "columns" to retrieve the values individually. How can i modify my "parseJSONResponse" method to achieve this?
I am trying to get the json data from properties file in java.
emailServer.properties
{
"Servers":
[
{
"Name":"Server1",
"UserName":"abcde#yahoo.in",
"Password":"something",
"Port":"993",
"FolderName":"Server1"
},
{
"Name":"Server2",
"UserName":"fghijk#gmail.co",
"Password":"something",
"Port":"993",
"FolderName":"Server2"
}
]
}
When i am trying to get servers array it is showing The method getJSONArray(String) is undefined for the type JSONObject. How to solve this?
Here is my java code :-
public void configure()
{
JSONParser parser = new JSONParser();
try
{
String propertyFileName = "emailServer.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propertyFileName);
JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(inputStream, "StandardCharsets.UTF_8"));
System.out.println(jsonObject);
JSONArray jadata = jsonObject.getJSONArray("Servers");
System.out.println(jadata);
}
catch (Exception e)
{
e.printStackTrace();
}
}
Instead of using
jsonObject.getJSONArray("Servers"),
you can use
JSONArray jadata =(JSONArray)jsonObject.get("Servers")
which may can solve your problem or if you still getting the issues then you can use google json library like Gson which you can find on maven and use below line:
yourjsonPojo[] data = gson.fromJson(jsonString, yourjsonPojo[].class);
I created one Java lambda function and deploy that function to Amazon API gateway.
I want to return JSONObject with inner JSONArray.
But I got { } empty JSONObject in response.
If I set jsonobjetc.toString() in response, That will work perfectly.
But if I return JSONObject I will return empty {} JSON response.
Am I missing something?
JSONObject mainJsonObject;
#Override
public Object handleRequest(Object input, Context context) {
inputHashMap = (LinkedHashMap) input;
responseJSON = new ResponseJSON();
mainJsonObject = new JSONObject();
saveDataToDynamoDB(inputHashMap);
return mainJsonObject;
}
public void saveDataToDynamoDB(LinkedHashMap inHashMap){
String login_id = (String) inputHashMap.get("login_id");
String first_name = (String) inputHashMap.get("first_name");
String last_name = (String) inputHashMap.get("last_name");
try{
DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient());
Table tableUserDetails = dynamoDB.getTable(USER_PROFILE_TABLE);
Item userProfileTableItem = new Item().withPrimaryKey("login_id", login_id)
.withString("first_name", first_name).withString("last_name", last_name);
tableUserDetails.putItem(userProfileTableItem);
mainJsonObject.put("status", "Success");
mainJsonObject.put("message", "Profile saved successfully.");
mainJsonObject.put("login_id", login_id);
mainJsonObject.put("first_name", first_name);
mainJsonObject.put("last_name", last_name);
}catch(Exception e){
try {
mainJsonObject.put("status", "Failed");
mainJsonObject.put("message", "Failed to saved profile data.");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
In case you are calling this code from HTTP request of a web service & catch the response result in your application, then your response should be in String format (String representation of JSON object).
After you get the response in String format, then parse the JSON string to JSON Object & do your further logic.
I have the following JSON string
String JSON = {"IP":{"string":"1.2.3.4"},"UrlParameters":{"map":{"pw":"36","mu":"www.abc.com"}}}
I need to get the value of pw and mu in Java. How do I parse it?
You may try this:
public static void main(String[] args) throws JSONException{
// TODO Auto-generated method stub
String JSON = "{\"IP\":{\"string\":\"1.2.3.4\"},\"UrlParameters\":{\"map\":{\"pw\":\"36\",\"mu\":\"www.abc.com\"}}}";
JSONObject jsonObject = new JSONObject(JSON);
System.out.println("Full JSON String: "+jsonObject);
JSONObject urlParametersMap = jsonObject.getJSONObject("UrlParameters").getJSONObject("map");
System.out.println("mu: "+urlParametersMap.getString("mu"));
System.out.println("pw: "+urlParametersMap.getString("pw"));
}
I'm constructiong a JSONObject in my javascript and then sending it as a string to my servlet using this code:
insertDtls = function() {
var jsonObj = [];
jsonObj.push({location: this.location()});
jsonObj.push({value: this.value()});
jsonObj.push({coverage: this.coverage()});
jsonObj.push({validPeriod: this.collateralValidPer()});
jsonObj.push({description: this.description()});
var b = JSON.stringify(jsonObj);
console.log(b.toString());
$.ajax({
url:"/HDSWFHub/AppProxy",
type: 'GET',
data: $.extend({WrJOB: "insertDtls", mainData: b}, tJS.getCommonPostData()),
dataType: "json",
success: function(responseText, status, xhr){
updateViewModel(responseText);
},
error: function(jqXHR, textStatus, error){
tJS.manageError(jqXHR);
}
});
},
The string looks like:
[{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}] and the servlet receives it without a problem.
Then I'm getting this in my servlet:
String step = request.getParameter("mainData");
JSONObject jsonObj = new JSONObject();
final JSONObject obj = new JSONObject();
System.out.println(step);
try {
obj.put("viewModel", "index");
obj.put("WrSESSIONTICKET", sessionTicket);
response.getWriter().print(obj.toString());
} catch (final Exception e) {
logException(request, response, e, true);
}
I'm trying to convert the JSON string back to object in the servlet in order to be able to loop trough the items, or to get the needed one. The library I'm using is org.json
I have tired:
JSONObject jsonObj = new JSONObject(step);
Without any success. Just got this error:
Unhandled exception type JSONException
I don't know what is happening. Maybe I'm too tired already. I'm sure that I'm missing something really small, but I'm unable to spot it.
I know that it has been asked hundreds of times. I know that I will get tons of downvotes, but I was unable to find an answer for my issue.
I tried the string you posted in your comment and it works fine. Here is the full code:
import org.json.JSONArray;
import org.json.JSONException;
public class jsonArray {
public static void main(String[] args) {
String text = "[{\"location\":\"Boston\"},{\"value\":\"5\"},{\"coverage\":\"15\"},{\"validPeriod\":\"08/05/2013\"},{\"description\":\"test description\"}]";
try {
JSONArray jsonArray = new JSONArray(text);
System.out.println(jsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
p.s. I am using org.json-20120521.jar library
Here your json String is converted to JSONObject .
In your case its not happening because [] brackets denotes Array. so first it is Array and then {} JSONObject in case of your String.
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
static String str = "[{\"location\":\"Boston\"},{\"value\":\"5\"},{\"coverage\":\"15\"},{\"validPeriod\":\"08/05/2013\"},{\"description\":\"test description\"}]";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JSONArray jsonArr = new JSONArray(str);
System.out.println("JSON ARRAY IS : ");
System.out.println(jsonArr.toString());
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println();
System.out.println(i+" JSON OBJECT IS : ");
System.out.println(jsonObj.toString());
}
} catch (org.json.JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
JSON ARRAY IS :
[{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}]
0 JSON OBJECT IS :
{"location":"Boston"}
1 JSON OBJECT IS :
{"value":"5"}
2 JSON OBJECT IS :
{"coverage":"15"}
3 JSON OBJECT IS :
{"validPeriod":"08/05/2013"}
4 JSON OBJECT IS :
{"description":"test description"}