Why JSONArray is throwing ClassNotFound Exception from JSP? - json

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!

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

invalid utf-8 start byte 0xb0

In Java, I am adding some properties to a JSON object, and sending those values to an HTTPS URL (REST API). The server throws some error like "invalid utf-8 start byte 0xb0". Below is my code:
final String urlString = "https://connect.pointclickcare.com/api/public/preview1/orgs/"+vitalStat.get("customer")+"/observations";
String authorization = "Bearer "+vitalStat.get("accessToken");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", vitalStat.get("type"));
jsonObject.addProperty("patientId", patientInfo.getPatientId());
jsonObject.addProperty("deviceId", vitalStat.get("deviceId"));
jsonObject.addProperty("deviceName", vitalStat.get("deviceName"));
jsonObject.addProperty("recordedDate", vitalStat.get("recordedDate"));
jsonObject.addProperty("value", vitalStat.get("value"));
jsonObject.addProperty("method", vitalStat.get("method"));
if(vitalStat.get("type").equals("temperature"))
{
jsonObject.addProperty("unit", "°F");
}
else{
jsonObject.addProperty("unit", vitalStat.get("unit"));
}
if(vitalStat.get("type").equals("bloodPressure"))
{
String[] split = vitalStat.get("value").split("/");
jsonObject.addProperty("systolicValue", split[0]);
jsonObject.addProperty("diastolicValue", split[1]);
jsonObject.remove("value");
}
HttpURLConnection connection = null;
try {
final URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.POST);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",MediaType.APPLICATION_JSON);
connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);
connection.setRequestProperty("Authorization", authorization);
final OutputStream outputStream = connection.getOutputStream();
final DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeBytes(jsonObject.toString());
dataOutputStream.close();
System.out.println(connection.getResponseMessage());
You don't want to use DataOutputStream. It has its own data encoding and is certainly not compatible with JSON. Instead, you have to serialize your JSON data such that a string representation of JSON (in UTF-8) is generated.
I assume that you are using JsonObject from org.json. In that case, the code should looks something like this:
final OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
jsonObject.write(writer);

JSON.NET: getting json from external source with streams, how to get just one value?

I have the following code:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
using (Stream stream = client.GetStreamAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result)
using (StreamReader streamReader = new StreamReader(stream))
using (JsonReader reader = new JsonTextReader(streamReader))
{
JsonSerializer serializer = new JsonSerializer();
// read the json from a stream
// json size doesn't matter because only a small piece is read at a time from the HTTP request
//What do I do here to get my one value?
}
Console.WriteLine("Press any key to continue...");
Console.Read();
}
I got this from the documentation over at the JSON.NET website. The reason being that I don't want to load the whole string, but piece by piece. The response is as follows:
[{"brandstof_omschrijving":"Benzine","brandstof_volgnummer":"1","brandstofverbruik_buiten":"6.60","brandstofverbruik_gecombineerd":"8.20","brandstofverbruik_stad":"11.10","co2_uitstoot_gecombineerd":"196","emissiecode_omschrijving":"Euro 4","geluidsniveau_rijdend":"71","geluidsniveau_stationair":"82","kenteken":"61SFSL","milieuklasse_eg_goedkeuring_licht":"70/220*2001/100B","nettomaximumvermogen":"99.00","toerental_geluidsniveau":"4125"}]
I.e., it returns an array with one json object, and I want to retrieve just one value in there, using a stream. How might I do this?
You could try the following
using System;
using System.Net.Http;
using Newtonsoft;
public class Program {
public static void Main() {
var client = new HttpClient();
var json = client.GetStringAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result;
var data = JsonConvert.DeserializeObject<dynamic>(json);
string value = data[0].co2_uitstoot_gecombineerd;
Console.WriteLine(value);
Console.WriteLine("Press any key to continue...");
Console.Read();
}
}

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/