In Java 9 new features are added and one of them is WebSocket, I have found articles related to sending text(string)/binary messages only. So, how to send JSON data over websocket using Java 9.
You can treat JSON similar to text. just deserialize it and send it as a plain text.
Write your data in StringWriter
StringWriter writer = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(writer, object);
String jsonText = writer.toString;
Now you have a String with your JSON.
Related
I am using WebServiceTemplate to consume SOAP response. For logging purpose i need to get the SOAP response in string.
For example , "<envelope><body><name>xyz</name></body></envelope>"
You can achive it like below with WebServiceTemplate:
ByteArrayOutputStream bytArrayOutputStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bytArrayOutputStream);
wsTemplate.sendSourceAndReceiveToResult(defautUri, source, result);
final String reply = new String(bytArrayOutputStream.toByteArray())
If you using spring, you can add log using log4j in interceptor. Log4j can write to file or even db. I hope its help you.
This source Google Finance option Chain Data returns the relaxed JSON, I wasn't able to Parse this JSON through PDI (Pentaho Data Integratio) (originally required) So thought of Parsing it in Java Code.
I tried using ObjectMapper and its Feature to allow unquoted field names but the json returned from above source is totally relaxed and can miss quotes anywhere.
String json = "{name:\"ankit\"}";
Map<String,String> map = new HashMap<String,String>();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(org.codehaus.jackson.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
map = mapper.readValue(json,new TypeReference<HashMap<String,String>>(){});
System.out.println(map);
It works fine if the keys in JSON are unquoted but fails if the same goes with values.
Is there any way out doing it with Pentaho Data integration or in Java Class.
I have a java class already serialized and stored as .ser format file but i want to get this converted in json file (.json format) , this is because serialization seems to be inefficient in terms of appending in direct manner, and further cause corruption of file due streamcorruption errors. Is there a possible efficient way to convert this java serialized file to json format.
You can read the .ser file as an InputStream and map the object received with key/value using Gson and write to .json file
InputStream ins = new ObjectInputStream(new FileInputStream("c:\\student.ser"));
Student student = (Student) ins.readObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(student );
try {
//write converted json data to a file named "file.json"
FileWriter writer = new FileWriter("c:\\file.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
There is no standard way to do it in Java and also there is no silver bullet - there are a lot of libraries for this. I prefer jackson https://github.com/FasterXML/jackson
ObjectMapper mapper = new ObjectMapper();
// object == ??? read from *.ser
String s = mapper.writeValueAsString(object);
You can see the list of libraries for JSON serialization/deserialization (for java and not only for java) here http://json.org/
this is because serialization seems to be inefficient in terms of appending in direct manner
Not sure if JSON is the answer for you. Could you share with us some examples of data and what manipulations you do with it?
You can try Google Protocol Buffers as alternative to Java serialization and JSON.
In my answer in topic bellow there is an overview of what GPB is and how to use, so you may check that and see if it suits you:
How to write/read binary files that represent objects?
I've written a small http server using Netty by following the example http server and now i'm trying to adapt it to my needs (a small app that should send json). I began by manually encoding my POJOs to json using jackson and then using the StringEncoder to get a ChannelBuffer. Now i'm trying to generalize it slightly by extracting the bit that encodes the POJOs to json by adding a HttpContentEncoder and I've managed to implement that more or less.
The part that i can't figure out is how to set the content on the HttpResponse. It expects a ChannelBuffer but how do i get my object into a ChannelBuffer?
Edit
Say i have a handler with code like below and have a HttpContentEncoder that knows how to serialize SomeSerializableObject. Then how do i get my content (SomeSerializableObject) to the HttpContentEncoder? That's what i'm looking for.
SomeSerializableObject obj = ...
// This won't work becuase the HttpMessage expects a ChannelBuffer
HttpRequest res = ...
res.setContent(obj);
Channel ch = ...
ch.write(res);
After looking into it a bit more though i'm unsure if this is what HttpContentEncoder is meant to do or rather do stuff like compression?
Most object serialization/deserialization libraries use InputStream and OutputStream. You could create a dynamic buffer (or a wrapped buffer for deserialization), wrap it with ChannelBufferOutputStream (or ChannelBufferInputStream) to feed the serialization library. For example:
// Deserialization
HttpMessage m = ...;
ChannelBuffer content = m.getContent();
InputStream in = new ChannelBufferInputStream(content);
Object contentObject = myDeserializer.decode(in);
// Serialization
HttpMessage m = ...;
Object contentObject = ...;
ChannelBuffer content = ChannelBuffers.dynamicBuffer();
OutputStream out = new ChannelBufferOutputStream(content);
mySerializer.encode(contentObject, out);
m.setContent(content);
If the serialization library allows you to use a byte array instead of streams, this can be much simpler using ChannelBuffer.array() and ChannelBuffer.arrayOffset().
I have a page that comes back as an UnexpectedPage in HtmlUnit, the response is JSON. Can I use HTMLUnit to parse this or will I need an additional library?
HtmlUnit doesn't support it. It can at highest execute a JS function. You need to check beforehand if the Content-Type of the returned response matches application/json and then use the suitable tool to parse it. Google Gson is useful in this.
WebClient client = new WebClient();
Page page = client.getPage("https://stackoverflow.com/users/flair/97901.json");
WebResponse response = page.getWebResponse();
if (response.getContentType().equals("application/json")) {
String json = response.getContentAsString();
Map<String, String> map = new Gson().fromJson(json, new TypeToken<Map<String, String>>() {}.getType());
System.out.println(map.get("displayName")); // Benju
}
If the JSON structure is known beforehand, you can even use Gson to convert it to a fullworthy Javabean. You can find an example in this answer.
BalusC provided a good answer, but to answer the literal question, you don't really need an additional library: you can use Groovy's neat built-in JsonSlurper, e.g:
def jsonSlurper = new groovy.json.JsonSlurper()
def parsed = jsonSlurper.parseText(response.getContentAsString())
println("Found ${parsed.TotalCount} records.");
to print out 1 for a response such as
'{"Records":[{"ID":"123","Address":"Zagreb",],"TotalCount":1}'