How to input a JSON byteCode (txt file) and parse it? - json

I made a JSON file and the I used FileOutputStream to save it as a text file in my hard drive . Then I use FileinputStream to input the file in a separated class. I use this code to print the JSON , but how can i parse it now using JSONParser .
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("D:\\XmlToJson.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
JSONArray jsonArray = (JSONArray) objectInputStream.readObject();

ObjectInputStream is not the correct class to use here. That is to read Java objects from Java's own serialisation scheme. Has nothing to do with JSON. And why JSONParser if you don't want to parse lazy and use the parse events to build some data structure other than a JSONArray then a JsonReader is the way to go.
Slightly adapted example from the Java documentation:
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("D:\\XmlToJson.txt");
JsonReader jsonReader = Json.createReader(fileInputStream);
JsonArray array = jsonReader.readArray();
jsonReader.close();
// ...
}

Related

How to test a Datastream with jsonobject in Apache Flink

I am new to testing and i am trying to write a unit test cases on a Flink Datastream which takes input a jsonobject and passes the json object to a processfuntion and it returns a valid or invalid jsonobject when certain rule conditions are met below is the junit test case, below i am trying to compare the output jsonobject from process function with the jsonobject of the input file
#Test
public void testcompareInputAndOutputDataJSONSignal() throws Exception {
org.json.JSONObject jsonObject = toJsonObject();
String input = jsonObject.toString();
String output = JSONDataStreamOutput();
assertEquals(mapper.readTree(input), mapper.readTree(output));
}
below is my toJSONObject and JSONDataStream meathods
public static JSONObject toJsonObject() throws IOException, ParseException {
JSONParser jsonParser = new JSONParser();
FileReader fileReader = new FileReader(getFileFromResources("input.json"));
JSONObject obj = (JSONObject) jsonParser.parse(fileReader);
return obj;
}
public String SignalDataStreamOutput() throws Exception {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<JSONObject> validSignal = env.fromElements(toJsonObject())
.process(new JsonFilter());
String outputFolder = "output";
validSignal.writeAsText(outputFolder).setParallelism(1);
env.execute();
String content = new String(Files.readAllBytes(Paths.get("output.txt")));
return content;
}
What i am doing is i am converting a jsonfile to jsonobject using the toJSONObject method and sending to a data stream using SignalDataStreamOutput method which will intern send it to a process function in JsonFilter class and validate it against a set of rules and if it's valid it will return a jsonobject and when trying to access the jsonobject directly from stream i am getting value like org.apache.flink#994jdkeiri so i am trying to write the output to a file and trying to read it back to a string and comparing it in test method but this is a work around process and i found a link to use Mockito framework here i changed it to use json object like below
final Collector<JSONObject> collectorMock = (Collector<JSONObject>)Mockito.mock(JsonFilter.class);
final Context contextMock = Mockito.mock(Context.class);
#Test
public void testcompareInputAndOutputDataForValidSignal() throws Exception {
org.json.JSONObject jsonObject = convertToJsonObject();
Mockito.verify(collectorMock).collect(jsonObject);
}
but the above approach is also not working can you suggest me simplified approach to test the json object

Loading json into my unit test from a text file

I am working in AEM trying to get create txt files with JSON output so that I can load them into my unit test as strings and test my model / model processors. So far I have this...
public String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
private String sampleInput = readFile("/test/resources/map/sample-
input.txt",Charset.forName("UTF-8"));
I need sampleInput to take the json that is in 'sampleInput.txt' and convert it to a string. I am also running into issues with the Charset encoding.
I think the easiest way to manage JSON documents you use for unit testing is by keeping them organized in the classpath. Guava provides a neat wrapper for loading classpath resources.
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import java.io.IOException;
import java.net.URL;
public class TestJsonDocumentLoader {
public TestJsonDocumentLoader(Class clazz) {
this.clazz = clazz;
}
public String loadTestJson(String fileName) {
URL url = Resources.getResource(clazz, fileName);
try {
String data = Resources.toString(url, Charsets.UTF_8);
return data;
} catch (IOException e) {
throw new RuntimeException("Couldn't load a JSON file.", e);
}
}
}
This can then be used to load arbitrary JSON files placed in the same package as the test class. It is assumed that the files are UTF-8 encoded. I suggest keeping all sources encoded that way, regardless of the OS your team is using. It saves you a lot of trouble with version control.
Let's say you have MyTest in src/test/java/com/example/mytestsuite, then you could place a file data.json in src/test/resources/com/example/mytestsuite and load id by calling
TestJsonDocumentLoader loader = new TestJsonDocumentLoader(MyTest.class);
String jsonData = loader.loadTestJson("data.json");
String someOtherExample = loader.loadTestJson("other.json");
Actually, this could be used for all sorts of text files.
You could have also used object mapper from Jackson as an alternative
public class JsonResourceObjectMapper<T> {
private Class<T> model;
public JsonResourceObjectMapper(Class<T> model) {
this.model = model;
}
public T loadTestJson(String fileName) throws IOException{
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream inputStream= classLoader.getResourceAsStream(fileName);
return new ObjectMapper().readValue(inputStream, this.model);
}
}
And then setup a fixture in the test passing a .class
private JsonClass json;
#Before
public void setUp() throws IOException {
JsonResourceObjectMapper mapper = new JsonResourceObjectMapper(JsonClass.class);
json = (JsonClass) mapper.loadTestJson("json/testJson.json");
}
Note that the testJson.json file is in resources/json folder same as what #toniedzwiedz mentioned
So then you could use the json model as:
#Test
public void testJsonNameProperty(){
//act
String name = json.getName();
// assert
assertEquals("testName", name);
}

Add Argument to existing Json String

I have this situation:
More servlets set the httpservletResponse content-type to json/application.
I output my json this way:
out.write (new Gson().toJson(myObject));
where myObject, is an object and the code above provides creating a string json like using myObject structure.
Now I need to add an argument on the top of the json, because I need an argument like: "result":"okay".
Is there a way to add this without changinc myObject class?
Thanks in advance.
Yes. Instead of building a String using Gson#toJson() use Gson#toJsonTree() which parses the object but creates a JSON internal representation using JsonElement subclasses. You will need to cast it to a JsonObject, then add the new property and finally write it to the output stream.
Code example:
package net.sargue.gson;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class SO36837061 {
public static class MyClass {
int a = 1;
String b = "salut";
}
public static void main(String[] args) {
MyClass myObject = new MyClass();
JsonObject jsonObject = (JsonObject) new Gson().toJsonTree(myObject);
jsonObject.addProperty("result", "okay");
String json = new Gson().toJson(jsonObject);
System.out.println("json = " + json);
}
}
Output:
json = {"a":1,"b":"salut","result":"okay"}

Java - Nested JSON objects

I am trying to create a simple JAVA remote for XBMC/KODI and I think im doing ok so far (still early days) but I have hit a snag when I reached a nested JSON object.
This is the original code I am converting to JAVA:
{"jsonrpc": "2.0", "method": "Player.PlayPause", "params": { "playerid": 0 }, "id": 1}
I have done this in JAVA so far:
public static void main(String[] args) throws UnknownHostException, IOException{
JSONObject json = new JSONObject();
json.put("jsonrpc", "2.0");
json.put("method", "Player.PlayPause");
//json.put("params", "playerid = 0"); THIS IS THE LINE I am having issues with
Socket s = new Socket("192.168.0.21", 8080);
try (OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8)) {
out.write(json.toString());
}}
As you can see from the original JSON there is a nested {} within the {} so {{}} and I dont know how to handle this. Im using JSON-Simple in eclipse if this helps, thanks for any help!
EDIT:
So that was helpful thanks, but it doesnt actually work is there anything wrong with the syntax:
public static void main(String[] args) throws UnknownHostException, IOException{
JSONObject json = new JSONObject();
JSONObject params = new JSONObject();
json.put("jsonrpc", "2.0");
json.put("method", "Player.PlayPause");
params.put("playerid", 0);
json.put("params", params);
json.put("id", 1);
Socket s = new Socket("192.168.0.21", 8080);
try (OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8)) {
out.write(json.toString());
}
}
Create another JSONObject for the params, set it up, and add it to the parent JSONObject with the key params.
//import java.util.ArrayList;
//import org.bson.Document;
Document root= new Document();
Document rootParams = new Document();
root.append("jsonrpc","2.0");
root.append("method","Player.PlayPause");
rootParams.append("playerid",0);
root.append("id",1);
if (!rootParams.isEmpty()){
root.append("params",rootParams);
}
System.out.println(root.toJson());

Retrieving JSON Object Literal from HttpServletRequest

I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.
Any insight is appreciated.
Thanks.
are you looking for this ?
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
}
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:
BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON or other object with Gson, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..
If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.
Converting the retreived data from the request object to json object is as below using google-gson
Gson gson = new Gson();
ABCClass c1 = gson.fromJson(data, ABCClass.class);
//ABC class is a class whose strcuture matches to the data variable retrieved