java restful web services retrieving post data - json

I am getting a JSON object POST request from android volley.I am trying to read the json using the following code.
#POST
#Path("/driver/insertTripLog")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_PLAIN)
public String insertTripLog(InputStream incomingData) throws Exception
{
StringBuilder sb = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
String data=sb.toString();
System.out.println("Data Received: " +data );
return data;
}
The output i am getting json object but the special characters are encoded with %XX format.
Sample Output:
json=%5B%7B%22name%22%3A%22value%22%7D%5D
how to read properly post json data sent from volley.

Use the URLDecoder class to handle the percent encoded content which you are seeing:
String data = sb.toString();
data = java.net.URLDecoder.decode(data, "UTF-8");
Output:
json=[{"name":"value"}]

Related

How to deserialize twitter response to List<Status> twitter4j

I'm using rest-assured and twitter4j for testing twitter API.
All calls are made via RestAssured, twitter4j is used for Json response deserialization.
And what I want to do is to deserialize Json response from twitter - GET statuses/home_timeline which returns Array of Status objects(from twitter4j).
I can easily deserialize one Status object like here:
#Test
public void verifyTwitCreation() {
RequestSpecification spec = new RqBuilder()
.withStatus(textToPublish)
.build();
Response response = twitClient.createTwit(spec);
assertResponseCode(response, 200);
String json = response.getBody().asString();
Status status = null;
try {
status = TwitterObjectFactory.createStatus(json);
} catch (TwitterException e) {
e.printStackTrace();
}
System.out.println(status.toString());
}
But I don't know how to do the same for deserializing array of such Status objects.
Try extracting a list of statuses using JsonPath and then parse them using TwitterObjectFactory:
Response response = twitClient.createTwit(spec);
List<Map<Object, Object>> responseList = response.jsonPath().getList("$");
ObjectMapper mapper = new ObjectMapper();
List<Status> statuses = responseList.stream().map(s -> {
Status status = null;
try {
String json = mapper.writeValueAsString(s)
status = TwitterObjectFactory.createStatus(json);
} catch (TwitterException | IOException e) {
e.printStackTrace();
}
return status;
}).collect(Collectors.toList());
You could move try/catch during parsing to a separate method so it looks nicer:
public class TestClass {
#Test
public void verifyTwitCreation() {
RequestSpecification spec = new RqBuilder()
.withStatus(textToPublish)
.build();
Response response = twitClient.createTwit(spec);
List<Map<Object, Object>> responseList = response.jsonPath().getList("$");
List<Status> statuses = responseList.stream().map(TestClass::createStatus)
.collect(Collectors.toList());
}
private static Status createStatus(Map<Object, Object> jsonMap) {
Status status = null;
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(jsonMap);
status = TwitterObjectFactory.createStatus(json);
} catch (TwitterException | IOException e) {
e.printStackTrace();
}
return status;
}
}
Update:
Since JsonPath getList() returns list of maps we should convert all maps to JSON string so that it can be used by TwitterObjectFactory. Jackson's ObjectMapper is used in example, but any JSON parsing tool can be used.
I kinda solve my problem. I just generated POJOs from Json with this plugin - https://plugins.jetbrains.com/plugin/8634-robopojogenerator and than mapped Json with rest-assured
List<Status> statuses = Arrays.asList(response.as(Status[].class));
But still I will appreciate the answer for solution with using twitter4j

Consume jira rest with java

i'm using java and i want to consume the json in this url : http://jiraserver/rest/dev-status/latest/issue/detail?issueId=13879&applicationType=stash&dataType=repository
on the browser this url works perfectly and i get all json data needed but in my java program i get
java.io.IOException: Server returned HTTP response code: 400 for URL:
http://jiraserver/rest/dev-status/latest/issue/detail?issueId=13879&applicationType=stash&dataType=repository
public static void main(String[] args) {
System.out
.println(jsonGetRequest("http://jiraserver/rest/dev-status/latest/issue/detail?issueId=13879&applicationType=stash&dataType=repository
"));
}
private static String streamToString(InputStream inputStream) {
String text = new Scanner(inputStream, "UTF-8").useDelimiter("\\Z").next();
return text;
}
public static String jsonGetRequest(String urlQueryString) {
String json = null;
try {
URL url = new URL(urlQueryString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
InputStream inStream = connection.getInputStream();
json = streamToString(inStream); // input stream to string
} catch (IOException ex) {
ex.printStackTrace();
}
return json;
}
am i missing something ? if there's any simple implementation to consume that url feel free

How to access nested JSON with array in firebase

I want to access a JSON of this structure in firebase
The structure
{
"questions":{
"English":{
"English_2002":[
{
"correct_ans":"A",
"OptionA":"a coder",
"OptionB":"a hacker",
"OptionC":"a writer",
"OptionD":"a programmer",
"Question":"Who build software"
},
{},
{}
],
"English_2003":[],
}
}
}
I want this structure. In the subject structure, other subjects will come after I exhaust 9 years of English.
My confusion is how to logically get each subject since firebase will only accept the root name questions.
Please I may sound dumb, but I have a very long questions thread almost 55000 lines. Because firebase accept one JSON tree.
Sorry i wasn't very clear i was asking from the stack phone app:
I have a question json tag of the structure above; my question is how will i be able to access the object subject like "english":{
// then accessing the first english array "english":[]
//since am now using firebase.
}
initially each array was individual json file, i have to recreate them into one for firebase sake. this is how i was parsing it then.
public class QuestionParser {
Context context;
public QuestionParser(Context c) {
this.context = c;
}
public ArrayList<Question> getJsonFromUrl(String url, String arrayName)
{
ArrayList<Question> arrayofQuestion = new ArrayList<>();
return arrayofQuestion;
}
// Processing question from JSon file in res > raw folder
public ArrayList<Question> parseQuestionJson(int rawJsonFileId, String arrayName) {
ArrayList<Question> questionList = new ArrayList<>();
String jsonstr = null;
try {
InputStream in = context.getResources().openRawResource(rawJsonFileId);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
jsonstr = sb.toString();
Log.d("REEEEADDD" + this.toString(), jsonstr);
//System.out.println(jsonstr);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(jsonstr)) {
return null;
}
try {
JSONObject jsonObject = new JSONObject(jsonstr);
JSONArray jsonArray = jsonObject.getJSONArray(arrayName);
JSONObject jobject;
for (int i = 0; i < jsonArray.length(); i++) {
// TEST
jobject = jsonArray.getJSONObject(i);
String ans = jobject.getString("correct_answer");
String graphic_name = jobject.getString("question_image");
String optionA = jobject.getString("optiona");
String optionB = jobject.getString("optionb");
String optionC = jobject.getString("optionc");
String optionD = jobject.getString("optiond");
String questionNo = jobject.getString("question_number");
String question = jobject.getString("question");
questionList.add(new Question(questionNo, graphic_name, question, optionA, optionB, optionC, optionD, ans));
Log.d("DDD" + this.toString(), String.valueOf(questionList.get(i)));
}
Log.i("ONE QUESTION", questionList.get(50).getQuestion());
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return questionList;
}
}
So how can i parse it from firebase because initially, if a student chooses question and year i passes those value as parameter and use them for parsing. but in firebase now i have access to only root firebase name in the get reference e method
To access for example "correct_ans":"A" you would query your firebase like so:
your.firebase.domain/questions/English/English_2002/0/correct_ans
Notice that each level in the json object is represented by a / and the key you want to access whereas in case of an array you simple add the array index. JSON's simple structure also allows simple REST like access

How to convert XML SOAP String to JSONObject (com.ibm.json.java.JSONObject)

Good Day,
I have created a java class in Adapter IBM Mobilefirst Platform that will get response from the Jax-ws service.
// read direct to soap service - 4/4/2017
protected JSONObject createJsonObjectFrmSOAPRequest(Map mapsData) throws IOException, SOAPException {
JSONObject jsonObj = new JSONObject();
String responseSoap="";
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
try {
// Send SOAP Message to SOAP Server
String url = "http://XXXXX:001/test-pvr-ws/empl_get";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(mapsData), url);
// Process the SOAP Response
responseSoap = printSOAPResponse(soapResponse);
// how to convert to jsonobject, the output is in xml string
// XMLToJSONTransformer.transform(responseSoap); - don't know how to use XMLToJSONTransformer
//JSONObject.parse(responseSoap); // convert String to JSONObject
logger.info("jsonObject : " + jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
protected String printSOAPResponse(SOAPMessage soapResponse) throws Exception {
String finalstringEnv = "";
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
System.out.print("\nResponse SOAP Message = ");
//create a StringWriter for the output
StringWriter outWriter = new StringWriter();
// StreamResult result = new StreamResult(System.out); // this is for print line output
StreamResult result = new StreamResult(outWriter);
transformer.transform(sourceContent, result);
// how to convert Transformer.transform() to String java
StringBuffer sb = outWriter.getBuffer();
finalstringEnv = sb.toString();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return finalstringEnv;
}
2 . This code will get the Response in XML string, but I don't know how to use library com.ibm.json.*. Which I wanted to convert the String Response to JSONObject.
2.1. Result Response in XML Soap Envelope (example successful Result i got).
<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<a:getTheResponse xmlns:a="http://XXXXX:001/test-pvr-ws/empl_get/">
<getTheRecord>
<statusCode>0</statusCode>
<getTheRecord>
<userid>1212</userid>
</a:getTheResponse>
</soapenv:Body>
</soapenv:Envelope>
2.2. responseSoap String variable i need to convert String XML Soap response To JSONObject
// Process the SOAP Response
responseSoap = printSOAPResponse(soapResponse);
//.............. code to convert String XML Soap response To JSONObject
I answer my Question:
Recently I just trying , I need to use this method XMLToJSONTransformer (com.ibm.json.xml.XMLToJSONTransformer) to convert the XML string to JSONObject.
String jsonObjectStr ="";
// convert String to JSONObject
jsonObjectStr = xmlToJsonTransformer.transform(responseSoap);
jsonObj = JSONObject.parse(jsonObjectStr);

JSON Exceptionorg.json.JSONException: Unterminated string at character

Im unable to get complete JSON string, it doesn't show last three character if the string. Here is JSON String
{"status":"success","data":"Screenshot_2016-07-24-13-06-4120160726082711.pn
JSON request
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Utils.psLog("Server RESPONSE >> " + response);
JSONObject obj = new JSONObject(response);
}
catch {
}
Error log
07-26 13:57:11.556 8632-8632/com.directory D/TEAMPS: Server RESPONSE >>
{"status":"success","data":"Screenshot_2016-07-24-13-06-4120160726082711.pn
07-26 13:57:11.557 8632-8632/com.directory D/TEAMPS: JSON Exceptionorg.json.JSONException: Unterminated string at character 78 of
{"status":"success","data":"Screenshot_2016-07-24-13-06-4120160726082711.pn
You are getting that error because the JSON Object appears to be incomplete (according do your code snippet).
If the string composing the JSON is incomplete, it will cause a JSON Parsing Exception
{"status":"success","data":"Screenshot_2016-07-24-13-06-4120160726082711.pn
Should instead be :
{"status":"success","data":"Screenshot_2016-07-24-13-06-4120160726082711.png"}