Unable to retrieve data from POST request - java

I am working in JAVA 1.8 to write and using Apache Tomcat to run the server, I am unable to retrieve data from a POST request i.e in JSON.
I actually need it in an HashMap and I can even parse and convert it into HashMap even if it is readable in JSON. I have tried several links on the internet and I always get exception like Could not deserialize to type interface PACKAGE NAME.
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("ClassifyCase")
public Rules Classify(HttpServletRequest request) {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { System.out.println("Buffer Reader Error"); }
System.out.println("What I read: "+jb);
System.out.println("Here la la l ala ");
// System.out.println("Case: ++ "+Case.toString());
System.out.println("Here la la l ala ");
Rules foundRule = new Rules();
// List<Rules> objListRules = new ArrayList<Rules>();
try
{
DataAccessInterface objDAInterface = new RuleDataAdapter();
AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
// foundRule = objADBridge.Classify(Case);
logger.info("Classification done!");
}
catch(Exception ex)
{
logger.info("Error in classification");
System.out.println("Couldnt Classify Properly!");
// return
}
return foundRule;
}
Can someone please share a guide on how can I receive this data and convert it into a Map or either I can directly get a Map!

I strongly recommend you to use this library of JSON..
You can find it in Maven Repository and it's so easy to parse a JSON to a Map or to a JSONArray or JSONObject... depends of your necessity what you want to do..
Here is a example show how to parse a JSON to a HashMap
Map<String, Object> map = new JSONObject(--JSONString here--).toMap();
And that's all...
Now, if your JSON has a list of objects, i mean like a list of maps, what you just need to do is this...
JSONArray jsonArray = new JSONArray(--JSON string here--);
for(int i = 0; i < jsonArray.length(); i++){
Map<String, Object> map = jsonArray.getJSONObject(i).toMap();
}
Here is the explanation.
You take you JSON string and pass it as a parameter to the JSONArray,what JSONArray does is, take your json string a parse it to like a list
Then you make a for to get each Object of that list and parse it to a map.
Note: what the JSONObject does, is take the object of the JSONArray and parse it... you can parse it to a map or you can get each object of that map..

String jsonString = "{\n" +
"\t\"1\": \"1\",\n" +
"\t\"FPG\": \"50\",\n" +
"\t\"Symptoms\": \"Yes\"\n" +
"}";
Map<String, String> map = new Gson().fromJson(jsonString, Map.class);
for (String key: map.keySet()) {
System.out.println(map.get(key));
}

The request you send does not contain proper JSON in the body. You are missing the commas ",". It should be something like this:
{
"1":"1",
"FPG":"50",
"Symptoms":"yes"
}
Just change it and give proper JSON format to the message.
Even if the request was not in your control, I would strongly suggest that you contacted the service that creates the message and asked from them to fix it.
It would be the last resort for me to make my own deserializer to handle an "inproper" message.
An easy way to check if your JSON is properly formated is an online formatter, e.g. https://jsonformatter.org/

Related

get a key value pair from a String json (simple object)

Im trying to get a key:value pair from a simple jsonString to add it after into a memory tab. If facing an issue cause my input is a string. and it looks like my loop isnot able to read the key value pair.
I read many topics about it, and im still in trouble with it. As you can see below
{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}
and my method, find only on object... the result is the same in my loop
public static ArrayHandler jsonSimpleObjectToTab(String data) throws ParseException {
if( data instanceof String) {
final var jsonParser = new JSONParser();
final var object = jsonParser.parse(data);
final var array = new JSONArray();
array.put(object);
final var handler = new ArrayHandler("BW_funct_Struct");
for( KeyValuePair element : array) {
handler.addCell(element);
Log.warn(handler);
}
return handler;
} else {
throw new IllegalArgumentException("jsonSimpleObjectToTab: do not support complex object" + data + "to Tab");
}
}
i also tryed before to type my array as a List, Object etc, without the keyValuePair object, i would appreciate some help.
Thanks again dear StackOverFlowers ;)
You can try this :
const json = '{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}';
map = new Map();
const obj = JSON.parse(json,(key,value) => {
map.set(key,value)
});
and you'll have every pair stored in map
Simply split the whole line at the commas and then split the resulting parts at the colon. This should give you the individual parts for your names and values.
Try:
supposing
String input = "\"nom\":\"BRUN\",\"prenom\":\"Albert\"";
then
String[] nameValuePairs = input.split(",");
for(String pair : nameValuePairs)
{
String[] nameValue = pair.split(":");
String name = nameValue[0]; // use it as you need it ...
String value = nameValue[1]; // use it as you need it ...
}
You can use TypeReference to convert to Map<String,String> so that you have key value pair.
String json = "{\"nom\":\"BRUN\",\"prenom\":\"Albert\",\"date_naiss\":\"10-10-1960\",\"adr_email\":\"abrun#gmail.com\",\"titre\":\"Mr\",\"sexe\":\"F\"}";
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<Map<String,String>> typeReference = new TypeReference<Map<String, String>>() {
};
Map<String,String> map = objectMapper.readValue(json, typeReference);
I just answered a very similar question. The gist of it is that you need to parse your Json String into some Object. In your case you can parse it to Map. Here is the link to the question with my answer. But here is a short version: you can use any Json library but the recommended ones would be Jackson Json (also known as faster XML) or Gson(by Google) Here is their user guide site. To parse your Json text to a class instance you can use ObjectMapper class which is part of Jackson-Json library. For example
public <T> T readValue(String content,
TypeReference valueTypeRef)
throws IOException,
JsonParseException,
JsonMappingException
See Javadoc. But also I may suggest a very simple JsonUtils class which is a thin wrapper over ObjectMapper class. Your code could be as simple as this:
Map<String, Object> map;
try {
map = JsonUtils.readObjectFromJsonString(input , Map.class);
} catch(IOException ioe) {
....
}
Here is a Javadoc for JsonUtils class. This class is a part of MgntUtils open source library written and maintained by me. You can get it as Maven artifacts or from the Github

Getting simple Json string from url and converting it to String[] Android

I am trying to pull Json string from url and put it into String[] inside my android application.
String i am getting from my url is "[\"What is your name?\",\"How do you do?\"]"
I am trying to create Quizz class in my app where i want to call constructor and then it pull data from url and put it into private variables.
I have tried many things but getting multiple errors (with network and other stuff) and now i am somewhere with async tasks where i got lost and think i am going totally wrong way.
Class i want to have is like this:
public class Quizz {
private String[] Questions;
public Quizz() {
// Here i want to load data from url into variable Questions
}
public String getQuestion(int id) {
return "Not implemented!";
}
}
And when i create Quizz object in my main activity i want to have questions loaded.
you can use the following article to help you decode your json
Article Link
Also, You can use JSONArray in the Following Article
Use Retrofit to Connect to API, and Use its converter to deserialize the JSON Response.
https://www.journaldev.com/13639/retrofit-android-example-tutorial
it's very effective and has error handling built into it.
I know you are looking for a string[] array but in this case its best to use a arraylist as sizes can change when retrieving the response.
//create empty strings arraylist
List<String> strings = new Arraylist<>()
//try parse the response as a JSONarray object
try{
//get url string response as a json array
JSONArray jsonArray = (JSONArray) urlStringResponse;
//parse through json array and add to list
for(int i = 0; i < jsonArray.length(); i++){
String str = (String) jsonArray.getJSONObject(i);
strings.add(str);
}
} catch (JSONException e) {
Log.e("JSON", "Problem parsing the JSON results", e);
}
What about to use String.split() method?
val string = "[\"What is your name?\",\"How do you do?\"]"
val split: List<String> = string.subSequence(1, string.length - 1).split(',')
val array = split.toTypedArray()
array.forEach { println(it) }
And result will be
"What is your name?"
"How do you do?"

Query a JSON Object in Java by index

In Java, is there a way to retrieve a piece of information from a JSON object by index? I am accessing a financial data table on quandl and want to return the most recent mortgage rate posted in the table. The key is the date the rate was posted in string form. The key for the most recent data will change weekly but the data I want will always be the first key-value pair in the table.
I was able to do this in JavaScript in about 5 minutes. But it seems more cumbersome in Java. Below is the iteration of my code that seems to be closest to getting me where I want to go. I am able to return the first key-value pair set in the table as an object in Java, which is ... ["2017-12-14",3.93]. The final step is eluding me. How do I grab the 3.93 and return that? Or is there a better way to go about this?
double baseRate = 0.0;
default double getBaseRate() throws MalformedURLException {
try {
// make a GET request
URL url = new URL("https://www.quandl.com/api/v3/datasets/FMAC/30US.json?api_key=-c-s9zf8s1NdLbhVin1p");
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
InputStreamReader is = new InputStreamReader((InputStream) request.getContent());
// Convert response stream to a JSON object
JsonReader reader = Json.createReader(is);
JsonObject obj = reader.readObject();
reader.close();
request.disconnect();
// Drill down to the desired piece of data
JsonObject dataset = obj.getJsonObject("dataset");
JsonArray data = dataset.getJsonArray("data");
Object currentData = data.get(0);
System.out.println(currentData);
} catch (IOException e) {
e.printStackTrace();
}
return baseRate;
}
I think that you need to go down another level of array to access the value you required.
JsonArray data = dataset.getJsonArray("data");
JsonArray firstPieceOfData = data.get(0);
Object firstRate = firstPieceOfData.get(1);
If you use Jackson for reading your JSON you can use the .at() method which allows you to access the node's value via a JSON Pointer Expression which in your case would be "/dataset/data/0/1"
I've truncated your json for the purpose of this demo:
String jsonString = "{\"dataset\":{\"id\":4644596,\"dataset_code\":\"30US\",\"database_code\":\"FMAC\",\"name\":\"30-Year Fixed Rate Mortgage Average in the United States\",\"description\":\"Units: Percent\\u003cbr\\u003e\\u003cbr\\u003eNot Seasonally Adjusted\",\"refreshed_at\":\"2017-12-18T04:09:32.892Z\",\"newest_available_date\":\"2017-12-14\",\"oldest_available_date\":\"1971-04-02\",\"column_names\":[\"Date\",\"Value\"],\"frequency\":\"weekly\",\"type\":\"Time Series\",\"premium\":false,\"limit\":null,\"transform\":null,\"column_index\":null,\"start_date\":\"1971-04-02\",\"end_date\":\"2017-12-14\",\"data\":[[\"2017-12-14\",3.93],[\"2017-12-07\",3.94],[\"2017-11-30\",3.9]],\"collapse\":null,\"order\":null,\"database_id\":582}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNodes = mapper.createObjectNode();
try {
jsonNodes = mapper.readTree(jsonString);
} catch (IOException e) {
//e.printStackTrace();
}
System.out.println(jsonNodes.at("/dataset/data/0/1").asDouble());// 3.93

libgdx Json parsing

hi I'm trying to get all 'id' value from my json into my 'results' array.
I didn't really understood how the json class of libgdx works, but I know how json works itself.
Here is the json : http://pastebin.com/qu71EnMx
Here is my code :
Array<Integer> results = new Array<Integer>();
Json jsonObject = new Json(OutputType.json);
JsonReader jsonReader = new JsonReader();
JsonValue jv = null;
JsonValue jv_array = null;
//
try {
String str = jsonObject.toJson(jsonString);
jv = jsonReader.parse(str);
} catch (SerializationException e) {
//show error
}
//
try {
jv_array = jv.get("table");
} catch (SerializationException e) {
//show error
}
//
for (int i = 0; i < jv_array.size; i++) {
//
try {
jv_array.get(i).get("name").asString();
results.add(new sic_PlayerInfos(
jv_array.get(i).get("id").asInt()
));
} catch (SerializationException e) {
//show error
}
}
Here is the error I get : 'Nullpointer' on jv_array.size
Doing it this way will result in a very hacky, not maintainable code. Your JSON file looks very simple but your code is terrible if you parse the whole JSON file yourself. Just imagine how it will look like if you are having more than an id, which is probably going to happen.
The much more clean way is object oriented. Create an object structure, which resembles the structure of your JSON file. In your case this might look like the following:
public class Data {
public Array<TableEntry> table;
}
public class TableEntry {
public int id;
}
Now you can easily deserialize the JSON with libgdx without any custom serializers, because libgdx uses reflection to handle most standard cases.
Json json = new Json();
json.setTypeName(null);
json.setUsePrototypes(false);
json.setIgnoreUnknownFields(true);
json.setOutputType(OutputType.json);
// I'm using your file as a String here, but you can supply the file as well
Data data = json.fromJson(Data.class, "{\"table\": [{\"id\": 1},{\"id\": 2},{\"id\": 3},{\"id\": 4}]}");
Now you've got a plain old java object (POJO) which contains all the information you need and you can process it however you want.
Array<Integer> results = new Array<Integer>();
for (TableEntry entry : data.table) {
results.add(entry.id);
}
Done. Very clean code and easily extendable.

cant convert json string to regular string array in java

iam trying to convert this json string back to an array but i can't seem to do it
["\"abba\"","\"repaper\"","\"minim\"","\"radar\"","\"murdrum\"","\"malayalam
\"","\"turrut\"","\"navan\""]
can anyone help, or point me in the right direction of some tutorials. Ive tried split(",") etc but im really not too sure how to extract the words themselves.
client code:
Gson gson;
String[] words = { "hello", "Abba", "repaper", "Minim", "radar",
"murdrum", "malayalam", "cheese", "turrut","Navan" };
gson = new Gson();
String json = gson.toJson(words);
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client
.resource("http://localhost:8090/RestSampleApp/rest/webservice/returnarray");
ClientResponse response = service.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, json);
String output = response.getEntity(String.class);
//String target2 = gson.fromJson(json, String.class);
System.out.println(output);
webservice code:
#POST
#Path("returnarray")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String returnstuff(String list) {
list2 = list.substring(1, list.length() - 1); //gets rid of "[]"
temp = new ArrayList<String>(Arrays.asList(list2.split(",")));
Algorithim algo = new Algorithim(temp); // instance of algorithim class takes in arrayList
algo.getpalindromesarray(); //creates plaindrome arraylist
newlist = algo.getnewlist();
String details = gson.toJson(newlist);
return details;
}
EDIT: My previous answer wasn't correct, see this new one...
You are not using Gson correctly... You are serializing the objects well, but you're not doing a correct deserialization... I suggest you to take a brief look to Gson documentation, it's few lines and you'll understand it better...
First you serialize your array correctly in your client, with:
String json = gson.toJson(words);
Then you send it using Jersey API, I think that it's correct (although I'm not an expert in Jersey...)
Then your problem is that you are not deserializing the JSON correctly in your web service. You should parse the JSON string passed as a parameter, and you can do it with Gson as well, like this:
Gson gson = new Gson();
Type listOfStringsType = new TypeToken<List<String>>() {}.getType();
List<String> parsedList = gson.fromJson(list, listOfStringsType);
Now you can do whatever you want with your list of words working with a proper Java List.
Once you finish your work, you serialize again the List to return it, with:
String details = gson.toJson(parsedList);
Now you have to repeat the deserializing operation in your client to parse the response and get again a List<String>...
Note: You should never try to do things like serialize/deserialize JSON (or XML...) manually. A manual solution may work fine in a particular situation, but it can't be easily adapted to changes, thus, if your JSON responses change, even only slightly, you'll have to change a lot of code... Always use libraries for this kind of things!
You'd better use json library, e.g. Jackson. If code yourself, you can do like below:
// 1st: remove [ and ]
s=s.substring(1, s.length()-1);
// 2nd: remove "
s=s.replaceAll("\"\"", "");
// 3rd: split
String[] parts = s.split(",");
You can try to use String.format to specify the format you waant to pass as part of your request.
For Ex :
WebResource webResource = client.resource("http://localhost:8090/RestSampleApp/rest/webservice/returnarray");
String input = String.format("{\manual format "}",parameter);
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
This is how I have acheived my goal

Categories

Resources