I am using jackson for converting POJO to JSON
User user = new User();
user.setAge(25);
user.setName("Shahid");
ObjectMapper mapper= new ObjectMapper();
mapper.writeValue("D:/test.json", user);
instead of writing it to file , I want to write it to on String variable (jsonString) . So that I get the result as follow.
String jsonString= "{"name" : "Shahid","age" : 25}";
You can try,
mapper.writeValueAsString(user).
Please refer documentation for more details.
You can try this:
OutputStream os = new ByteArrayOutputStream();
mapper.writeValue(os, user);
String json = os.toString();
Related
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.
Please suggest how to perform typecasting before validation of JSON Schema in Java. I've achieved the same in NodeJS using json-schema-validation-pipeline package. Below code snippet for reference (where param1 was actually of type string as provided from backend API).
var ValidationPipeline = require('json-schema-validation-pipeline');
var V = ValidationPipeline.V;
var validate = ValidationPipeline([
{
$schema: {
'param1': V(Number).min(60)
}
},
{ $cast: { param1: Number } }
]);
So basically, I am looking for equivalent solution in Java for above code snippet. Thanks
Assign it to POJO model class of JAVA and once you have this native object then you can typecast to anything as its in language operation For example-
File file = new File("json/student.json");
// get json as buffer
BufferedReader br = new BufferedReader(new FileReader(file));
// obtained Gson object
Gson gson = new Gson(); //import com.google.gson.Gson;
// called fromJson() method and passed incoming buffer from json file
// passed student class reference to convert converted result as Student object
Student student = gson.fromJson(br, Student.class);
When I use JSONArray and JSONObject to generate a JSON, whole JSON will be generated in one line. How can I have each record on a separate line?
It generates like this:
[{"key1":"value1","key2":"value2"}]
I need it to be like following:
[{
"key1":"value1",
"key2":"value2"
}]
You can use Pretty Print JSON Output (Jackson).
Bellow are some examples
Convert Object and print its output in JSON format.
User user = new User();
//...set user data
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
Pretty Print JSON String
String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"myname\"}";
Object json = mapper.readValue(test, Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
Reference : http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/
You may use of the google-gson library for beautifying your JSON string.
You can download the library from here
Sample code :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
OR
you can use org.json
Sample code :
JSONTokener tokener = new JSONTokener(uglyJsonString); //tokenize the ugly JSON string
JSONObject finalResult = new JSONObject(tokener); // convert it to JSON object
System.out.println(finalResult.toString(4)); // To string method prints it with specified indentation.
Refer answer from this post :
Pretty-Print JSON in Java
The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
and please refer this : https://stackoverflow.com/a/2614874/3164682
you can also beautify your string online here.. http://codebeautify.org/jsonviewer
For gettting a easy to read json file you can configure the ObjectMapper to Indent using the following:
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
I want convert json to xml
here is code
public class ConvertJSONtoXML {
public static void main(String[] args) throws Exception {
InputStream is = ConvertJSONtoXML.class.getResourceAsStream("demo1.txt");
String jsonData = IOUtils.toString(is);
XMLSerializer serializer = new XMLSerializer();
JSON json = JSONSerializer.toJSON(jsonData);
String xml = serializer.write((JSON) json);
System.out.println(xml);
Here is demo1.txt
{"name":"naveed" }
It reads demo1.txt file and convert into xml but i m trying to pass json as string.
String jsonString="{\"name\":\"naveed\" }";
InputStream is = ConvertJSONtoXML.class.getResourceAsStream(jsonString);
but it wont work for string..
i thing getResourceAsStream(jsonString) doesnt work for string....
please suggest any reference
The method getResourceAsStream() actually looks on the file system for resource identified by the input string and open an input stream for it.
You should rather use something like
InputStream is = new ByteArrayInputStream( jsonString.getBytes() );
Also, you should take care of using compatible charsets.
What I'm trying to do is to convert an object to xml, then use a String to transfer it via Web Service so another platform (.Net in this case) can read the xml and then deparse it into the same object. I've been reading this article:
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#start
And I've been able to do everything with no problems until here:
Serializer serializer = new Persister();
PacienteObj pac = new PacienteObj();
pac.idPaciente = "1";
pac.nomPaciente = "Sonia";
File result = new File("example.xml");
serializer.write(pac, result);
I know this will sound silly, but I can't find where Java creates the new File("example.xml"); so I can check the information.
And I wanna know if is there any way to convert that xml into a String instead of a File, because that's what I need exactly. I can't find that information at the article.
Thanks in advance.
And I wanna know if is there any way to convert that xml into a String instead of a File, because that's what I need exactly. I can't find that information at the article.
Check out the JavaDoc. There is a method that writes to a Writer, so you can hook it up to a StringWriter (which writes into a String):
StringWriter result = new StringWriter(expectedLength);
serializer.write(pac, result)
String s = result.toString();
You can use an instance of StringWriter:
Serializer serializer = new Persister();
PacienteObj pac = new PacienteObj();
pac.idPaciente = "1";
pac.nomPaciente = "Sonia";
StringWriter result = new StringWriter();
serializer.write(pac, result);
String xml = result.toString(); // xml now contains the serialized data
Log or print the below statement will tell you where the file is on the file system.
result.getAbsolutePath()