Java - Nested JSON objects - json

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());

Related

How do i return Json array using vertx routingcontext

I'm writing api using vertx router, and i need my api to return list of json object, is it possible? Thanks in advance
Yes its possible, here is a full example with vert.x json abstraction:
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
public class Main {
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
Router router = Router.router(vertx);
router.get("/foo")
.handler(ctx -> {
JsonArray jsonArray = new JsonArray();
jsonArray.add(new JsonObject());
jsonArray.add(new JsonObject());
ctx.response()
.setChunked(true)
.setStatusCode(200)
.end(jsonArray.toBuffer());
});
vertx
.createHttpServer()
.requestHandler(router)
.listen(8080);
}
}
In case you want to use your own library for json manipulation + pojos, you can work with strings instead when ending the request. e.g. with jackson:
router.get("/foo")
.handler(ctx -> {
List<MyObject> myObjectList = new ArrayList<>();
ObjectMapper objectMapper = new ObjectMapper();
String myObjectListJsonStr = objectMapper.writeValueAsString(myObjectList);
ctx.response()
.setChunked(true)
.setStatusCode(200)
.end(myObjectListJsonStr);
});

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

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();
// ...
}

how to include the json file in request body using httpClient?

how to include the json file in request body using httpClient?
My Json:
{
"products": {
"product": {
"sku": "100",
"varientsku": "0",
"mrp": "5,300",
"webprice": "5,220",
”inventory”: ”25”
}
}
}
My code:
public static void main(String args[])
{
uri=//url
JSONObject json=new JSONObject();
json.put("sku", "100");
json.put("mrp", "12121");
json.put("inventory", "2525");
JSONObject product=new JSONObject();
product.put("product", json);
JSONObject products=new JSONObject();
products.put("products", product);
HttpPost postRequest=new HttpPost(uri);
postRequest.addHeader("accept", "application/json");
postRequest.setHeader("ContentType", "application/json");
postRequest.setEntity(new StringEntity(products.toString(), "UTF-8"));
HttpResponse response=httpClient.execute(postRequest);
}
Read the file into memory and json_encode it.
in javascript:
var json = JSON.stringify(file);
in c#:
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(file);
Then what you have is a string with all the information in the file. Pass it as you would any string information. Then when you handle it (presumably in php?), json_decode it,
$jsonObject = json_encode($data['body']);
I hope this helps with your question. If not, please provide more information like what language you are using, and for what purpose you are using httpClient. The more information, the better.
~~UPDATED UPON REQUEST~~
For Java, it appears that people recommend using Apache's HttpClient library found: HERE, look at the first few chapters of the tutorial to see if it's what you want. You can download the library from them on that site as well.
For simple requests, some people will use HttpURLconnection by oracle (found HERE) example:
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream(); //read the contents using an InputStreamReader
I found this information HERE

Uncaught exception from servlet - JSON GAE deployment issue

I have created a script on browser that calls a servlet which is deployed on GAE. The servlet uses Datastore.
Everytime servlet is called I receive the following error
Uncaught exception from servlet java.lang.NoClassDefFoundError: org/json/JSONException
For development I use eclipse and Maven.
In pom.xml I have already included org.json 20090211 and javax.validation.
UPDATE
In order to better clarify my question I am posting code from servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = request.getReader();
String str;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
String jsonResp = sb.toString();
JSONParser gparser = new JSONParser();
The problem appears on the last line, so I am posting code from JSONParser
public class JSONParser {
public ArrayList<String> ReturnGoogleJSON(String ResponseString) throws IOException {
ArrayList<String> Row = new ArrayList<String>();
try {
JSONObject rootObject = new JSONObject(ResponseString); // Parse the JSON to a JSONObject
JSONArray rows = rootObject.getJSONArray("items") ; // Get all JSONArray rows
for(int i=0; i < rows.length(); i++) { // Loop over each each row
JSONObject element = rows.getJSONObject(i); // Get the element object
Row.add(element.getString("tag"));
Row.add(element.getString("link"));
Row.add(element.getString("priority"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return Row;
}
}
Could anyone help me with this kind of error?
Thank you in advance.
Check war/WEB-INF/lib directory of your project in eclipse before upload and make sure that json and other dependent files are present in this directory.
Edit:
You may want to check:
GAE - ClassNotFoundException after deployment to Appspot server
http://javanto.com/blog/2012/01/11/gae-eclipse-maven-2-0/

Why JSONArray is throwing ClassNotFound Exception from JSP?

Map countryList = new HashMap();
String str = "http://10.10.10.25/TEPortalIntegration/CustomerPortalAppIntegrationService.svc/PaymentSchedule/PEPL/Unit336";
try {
URL url = new URL(str);
URLConnection urlc = url.openConnection();
BufferedReader bfr = new BufferedReader(new InputStreamReader(
urlc.getInputStream()));
String line, des;
double title;
final StringBuilder builder = new StringBuilder(2048);
while ((line = bfr.readLine()) != null) {
builder.append(line);
}
// convert response to JSON array
final JSONArray jsa = new JSONArray(builder.toString());
// extract out data of interest
for (int i = 0; i < jsa.length(); i++) {
final JSONObject jo = (JSONObject) jsa.get(i);
title = jo.getDouble("NetAmount");
countryList.put(i, title);
}
System.out.println(countryList); /* Giving result if i run in Console*/
} catch (Exception e) {
// TODO: handle exception
}
renderRequest.setAttribute("out-string", countryList);
The above code is to consume JSON web services from java client. I am able to access it from java console application. But when trying with JSP or Liferay its not working. In JSP its giving java.lang.NoClassDefFoundError: org/json/JSONArray. Please help me to fix it.
Should i need to add any more jar files to the libraries to make it working in JSP?
You need to add the jar file containing JSONArray class in your web application as per this directory structure:
Tomcat_HOME
->
webapps
->
YourWebAppName
->
WEB-INF
->lib
->Here goes your jar file
Instead of using json.org.JSONArray, have you considered using Liferay's JSON API?
You can import:
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
They do something like:
JSONObject jsonObject = JSONFactoryUtil.createJSONObject(myJSONObjectString);
JSONArray jsonArray = JSONFactoryUtil.createJSONArray(myJSONArrayString);
This way there is no additional JAR required!