Modify JSON, using Java - java

Hello I have app that is generating JSON data. When i open the route /someData I can see the JSON as I want, but when I save it in file or print it in Eclipse it adds Object name before the data:
MyObjectSchema [latitude=45.95472, longitude=13.664836, Timezone=Europe,
currently={time=1459936800}...]
How can i delete MyObjectSchema that is before the list.
This is my code:
#Scheduled(fixedDelayString = "${fixedDelaySchema}", initialDelayString = "${initialDelaySchema}")
public MyObjectSchema createMySchema() throws IOException {
Map<String, ArrayList<MyObject>> map = new HashMap<String, ArrayList<MyObject>>();
map.put("data", (ArrayList<MyObject>) list1);
Map<String, Long> map1 = new HashMap<String, Long>();
map1.put("time", list1.get(0).getTime());
MyObjectSchema obj1 = new MyObjectSchema();
obj1.setLatitude(rf.getLatitude());
obj1.setLongitude(rf.getLongitude());
obj1.setTimezone(rf.getTimezone());
obj1.setCurrently(map1);
obj1.setHourly(map);
System.out.println(obj1);
listSchema.add(obj1);
if (list1.get(0).getTime() == 1460019600) {
String jsonString = obj1.toString();
String path = "test.json";
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream(path));
System.out.println("Start Writings");
outputStream.writeObject(jsonString);
outputStream.flush();
outputStream.close();
System.exit(0);
} catch (Exception e) {
System.err.println("Error: " + e);
}
}
return obj1;
}

obj1.toString() is calling the toString() method of your object MyObjectSchema which right now doesn't generate a JSON valid string. You could modify your toString() method in order to generate proper JSON by string concatenation, but I don't recommend it. Instead use a library like Jackson or Gson to easily create JSON from your objects.

I faced with similar problem in the past.
You can fix it like this:
String response = new Gson().toJson(listSchema);
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\Desktop\\file.json"));
writer.write(response);
writer.close();

Use Libraries like GSON.
To use Gson, declares the following dependency.
pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
// 1. Java object to JSON, and save into a file
gson.toJson(obj1, new FileWriter("D:\\test.json"));

Related

get a key value pair from a String json (simple object)

Im trying to get a key:value pair from a simple jsonString to add it after into a memory tab. If facing an issue cause my input is a string. and it looks like my loop isnot able to read the key value pair.
I read many topics about it, and im still in trouble with it. As you can see below
{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}
and my method, find only on object... the result is the same in my loop
public static ArrayHandler jsonSimpleObjectToTab(String data) throws ParseException {
if( data instanceof String) {
final var jsonParser = new JSONParser();
final var object = jsonParser.parse(data);
final var array = new JSONArray();
array.put(object);
final var handler = new ArrayHandler("BW_funct_Struct");
for( KeyValuePair element : array) {
handler.addCell(element);
Log.warn(handler);
}
return handler;
} else {
throw new IllegalArgumentException("jsonSimpleObjectToTab: do not support complex object" + data + "to Tab");
}
}
i also tryed before to type my array as a List, Object etc, without the keyValuePair object, i would appreciate some help.
Thanks again dear StackOverFlowers ;)
You can try this :
const json = '{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}';
map = new Map();
const obj = JSON.parse(json,(key,value) => {
map.set(key,value)
});
and you'll have every pair stored in map
Simply split the whole line at the commas and then split the resulting parts at the colon. This should give you the individual parts for your names and values.
Try:
supposing
String input = "\"nom\":\"BRUN\",\"prenom\":\"Albert\"";
then
String[] nameValuePairs = input.split(",");
for(String pair : nameValuePairs)
{
String[] nameValue = pair.split(":");
String name = nameValue[0]; // use it as you need it ...
String value = nameValue[1]; // use it as you need it ...
}
You can use TypeReference to convert to Map<String,String> so that you have key value pair.
String json = "{\"nom\":\"BRUN\",\"prenom\":\"Albert\",\"date_naiss\":\"10-10-1960\",\"adr_email\":\"abrun#gmail.com\",\"titre\":\"Mr\",\"sexe\":\"F\"}";
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<Map<String,String>> typeReference = new TypeReference<Map<String, String>>() {
};
Map<String,String> map = objectMapper.readValue(json, typeReference);
I just answered a very similar question. The gist of it is that you need to parse your Json String into some Object. In your case you can parse it to Map. Here is the link to the question with my answer. But here is a short version: you can use any Json library but the recommended ones would be Jackson Json (also known as faster XML) or Gson(by Google) Here is their user guide site. To parse your Json text to a class instance you can use ObjectMapper class which is part of Jackson-Json library. For example
public <T> T readValue(String content,
TypeReference valueTypeRef)
throws IOException,
JsonParseException,
JsonMappingException
See Javadoc. But also I may suggest a very simple JsonUtils class which is a thin wrapper over ObjectMapper class. Your code could be as simple as this:
Map<String, Object> map;
try {
map = JsonUtils.readObjectFromJsonString(input , Map.class);
} catch(IOException ioe) {
....
}
Here is a Javadoc for JsonUtils class. This class is a part of MgntUtils open source library written and maintained by me. You can get it as Maven artifacts or from the Github

Convert JSON String to File in Java

I'm trying to convert an Object to JSON then convert it to File
to be able to send it to AWS S3.
Is there a way to convert the String in the most efficient way?
Thank you!
Here is my code:
String messageBody = new Gson().toJson(thisIsADtoObject);
And for the S3
PutObjectRequest request = new PutObjectRequest(s3BucketName, key, file);
amazonS3.putObject(request);
As far as I know, to create a file object to send to AWS, you will have to create the actual file on disk, e.g. with a PrintStream:
File file = new File("path/to/your/file.name");
try (PrintStream out = new PrintStream(new FileOutputStream(file))) {
out.print(messageBody);
}
Instead of using the constructor taking a file, you might want to use the one which takes an InputStream:
PutObjectRequest request = new PutObjectRequest(s3BucketName, key, inputStream, metadata);
amazonS3.putObject(request);
To convert a String to an InputStream, use
new ByteArrayInputStream(messageBody.getBytes(StandardCharsets.UTF_8));
Link to SDK JavaDoc
public class JSONStringToFile {
public static void main(String[] args) throws IOException {
JSONObject obj = new JSONObject();
obj.put("Name", "somanna");
obj.put("city", "bangalore");
JSONArray company = new JSONArray();
company.add("Compnay: mps");
company.add("Compnay: paypal");
company.add("Compnay: google");
obj.put("Company List", company);
// try-with-resources statement based on post comment below :)
try (FileWriter file = new FileWriter("/Users/<username>/Documents/file1.txt")) {
file.write(obj.toJSONString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + obj);
}
}
}
It's much easier with version 2 of the AWS Java SDK.
If you have converted the object to a JSON String, using GSON or Jackson, you can upload it via:
PutObjectRequest putObjectRequest = PutObjectRequest.builder().bucket(bucket).key(s3Key).build();
s3Client.putObject(putObjectRequest, RequestBody.fromString(jsonString));
No need to set the content length manually.

Unable to retrieve data from POST request

I am working in JAVA 1.8 to write and using Apache Tomcat to run the server, I am unable to retrieve data from a POST request i.e in JSON.
I actually need it in an HashMap and I can even parse and convert it into HashMap even if it is readable in JSON. I have tried several links on the internet and I always get exception like Could not deserialize to type interface PACKAGE NAME.
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("ClassifyCase")
public Rules Classify(HttpServletRequest request) {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { System.out.println("Buffer Reader Error"); }
System.out.println("What I read: "+jb);
System.out.println("Here la la l ala ");
// System.out.println("Case: ++ "+Case.toString());
System.out.println("Here la la l ala ");
Rules foundRule = new Rules();
// List<Rules> objListRules = new ArrayList<Rules>();
try
{
DataAccessInterface objDAInterface = new RuleDataAdapter();
AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
// foundRule = objADBridge.Classify(Case);
logger.info("Classification done!");
}
catch(Exception ex)
{
logger.info("Error in classification");
System.out.println("Couldnt Classify Properly!");
// return
}
return foundRule;
}
Can someone please share a guide on how can I receive this data and convert it into a Map or either I can directly get a Map!
I strongly recommend you to use this library of JSON..
You can find it in Maven Repository and it's so easy to parse a JSON to a Map or to a JSONArray or JSONObject... depends of your necessity what you want to do..
Here is a example show how to parse a JSON to a HashMap
Map<String, Object> map = new JSONObject(--JSONString here--).toMap();
And that's all...
Now, if your JSON has a list of objects, i mean like a list of maps, what you just need to do is this...
JSONArray jsonArray = new JSONArray(--JSON string here--);
for(int i = 0; i < jsonArray.length(); i++){
Map<String, Object> map = jsonArray.getJSONObject(i).toMap();
}
Here is the explanation.
You take you JSON string and pass it as a parameter to the JSONArray,what JSONArray does is, take your json string a parse it to like a list
Then you make a for to get each Object of that list and parse it to a map.
Note: what the JSONObject does, is take the object of the JSONArray and parse it... you can parse it to a map or you can get each object of that map..
String jsonString = "{\n" +
"\t\"1\": \"1\",\n" +
"\t\"FPG\": \"50\",\n" +
"\t\"Symptoms\": \"Yes\"\n" +
"}";
Map<String, String> map = new Gson().fromJson(jsonString, Map.class);
for (String key: map.keySet()) {
System.out.println(map.get(key));
}
The request you send does not contain proper JSON in the body. You are missing the commas ",". It should be something like this:
{
"1":"1",
"FPG":"50",
"Symptoms":"yes"
}
Just change it and give proper JSON format to the message.
Even if the request was not in your control, I would strongly suggest that you contacted the service that creates the message and asked from them to fix it.
It would be the last resort for me to make my own deserializer to handle an "inproper" message.
An easy way to check if your JSON is properly formated is an online formatter, e.g. https://jsonformatter.org/

How can I somehow "store" a json file in a Spring-Boot program so my web app then reads this json

Basically, I'm writing my first Spring-Boot program, and I have to get a list of products stored on a JSON file to display each product using VueJS (I know how to use Vue, I just need to get the JSON data somewhere in the webpage or smth)
I spent last 3'5 hours looking at tutorials about consuming JSON's and POST stuff and none helped.
Lets call your file config.json.
In a typical maven project, keep your file at
src/main/resources/config.json
In your code, read it like
try {
ClassPathResource configFile = new ClassPathResource("config.json");
String json = IOUtils.toString(configFile.getInputStream(), Charset.forName(Util.UTF_8));
} catch (IOException e) {
String errMsg = "unexpected error while reading config file";
logger.error(errMsg, e);
throw new Exception(e);
}
After this, use Jackson or GSON to read the json into an object. From there you can either reference it directly as a static attribute or as an attribute in component as per your use case.
Hope this code will work for you
public class JsonReader{
public static void readFromJson() throws Exception {
InputStream inStream = JsonReader.class.getResourceAsStream("/" + "your_config_file.json");
Map<String, String> keyValueMap =
new ObjectMapper().readValue(inStream, new TypeReference<Map<String, String>>() {});
inStream.close();
}
}
You might need to add the maven dependency for ObjectMapper()

How to convert a POJO to Map<String, AttributeValue> for dynamo db?

I am using transaction for dynamodb. And transaction Put request takes com.amazonaws.services.dynamodbv2.document.Item as input param. So, I need to convert a POJO to a Map.
So far I have tried converting the object to string using Jackson and then converting the string to an item.
Below is the code I have tried.
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = null;
try {
jsonStr = objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Item item = new Item().withJSON("document", jsonStr);
Map<String,AttributeValue> attributes = ItemUtils.toAttributeValues(item);
return attributes.get("document").getM();
Problem is, a field of 'Set' type returns 'List' after conversion.
Any suggestion how to overcome this?
Below code should solve your convertion:
Map<String, AttributeValue> valueMap = ItemUtils.toAttributeValues(item);
CustomEntity entity = dynamoDBMapper.marshallIntoObject(CustomEntity.class, valueMap);

Categories

Resources