cant convert json string to regular string array in java - 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

Related

Is there a better way to Optimize code that takes one value out of a Request body, the data comes in, in json format

I have an request object, that contains a huge amount of data. But there is a filter in my code, where I need to take out just one element. At the moment I am Deserializing the whole object, which seems overkill to just get one element
This is part of a zuul filter
import com.netflix.zuul.context.RequestContext;
RequestContext ct = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
ObjectMapper mapper = new ObjectMapper();
ServletInputStream stream = null;
try {
stream = request.getInputStream();
GetPageRequest page = mapper.readValue(stream,GetPageRequest.class);
log.info("URL IN BODY "+page.getUrl());
It seems over kill to deserialize an entire object to get one element but I cant think of a more efficient and optomized way
At it's simplest the request payload can just be a string so you could read the input as a string and then parse what you want out using a regular expression or an indexOf or whatever suits best?
With thanks to everyone. I created this method. Streamed inputstream into a string Created a JSONObject which takes in and tokenizies the string
private String getURLFromRequest(ServletInputStream stream) throws IOException, JSONException {
String requestStr = IOUtils.toString(stream, "UTF-8");
JSONObject jsonObj = new JSONObject(requestStr);
return (String) jsonObj.get("url");
}

Unable to retrieve data from POST request

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/

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?"

Deserialize Retrofit2 response into JSON without Jackson

I am calling an API using Retrofit2 that is giving me a large and complicated response. This was fine since all I needed to do was deserialize the response into a String and then put it on an activeMQ.
However, now I would like to add two more Json attributes to the complicated response so that it looks like the following:
{
"event": "some event",
"link": "some link",
"details": {complicated response ...}
}
How do I deserialize a response as a Json (javax.json.Json), so then I can build onto it as a JsonObject with the new attributes, and then a String?
The JacksonConverterFactory forces me to fit this complicated response into POJOs and I do not want to do that! Right now I am adding strings to the top of the response, but this is not an ideal solution.
Assuming that your large and complicated response is in a string named input, you could perhaps do the following:
JsonReader reader = Json.createReader(new StringReader(input));
JsonObject response = reader.readObject();
JsonObject queueMessage =
Json.createObjectBuilder()
.add("event", "some event")
.add("link", "some link")
.add("details", response)
.build();
Another approach, which uses Jackson and doesn't force you to deserialize the complicated response into a structure of JSON-objects, is to use the #JsonRawValue annotation, which lets you mark a String field as already containing JSON that should be included verbatim during serialization.
This allows you to do something like:
public class MQMessage {
public String event, link;
#JsonRawValue
public String details;
}
MQMessage message = new MQMessage();
message.event = "some event";
message.link = "Some link";
message.details = input;
String forMQ = new ObjectMapper().writeValueAsString(message);
Be aware that Jackson doesn't do any verification that details actually contains valid JSON.

How to have each record of JSON on a separate line?

When I use JSONArray and JSONObject to generate a JSON, whole JSON will be generated in one line. How can I have each record on a separate line?
It generates like this:
[{"key1":"value1","key2":"value2"}]
I need it to be like following:
[{
"key1":"value1",
"key2":"value2"
}]
You can use Pretty Print JSON Output (Jackson).
Bellow are some examples
Convert Object and print its output in JSON format.
User user = new User();
//...set user data
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
Pretty Print JSON String
String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"myname\"}";
Object json = mapper.readValue(test, Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
Reference : http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/
You may use of the google-gson library for beautifying your JSON string.
You can download the library from here
Sample code :
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(uglyJSONString);
String prettyJsonString = gson.toJson(je);
OR
you can use org.json
Sample code :
JSONTokener tokener = new JSONTokener(uglyJsonString); //tokenize the ugly JSON string
JSONObject finalResult = new JSONObject(tokener); // convert it to JSON object
System.out.println(finalResult.toString(4)); // To string method prints it with specified indentation.
Refer answer from this post :
Pretty-Print JSON in Java
The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:
JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
and please refer this : https://stackoverflow.com/a/2614874/3164682
you can also beautify your string online here.. http://codebeautify.org/jsonviewer
For gettting a easy to read json file you can configure the ObjectMapper to Indent using the following:
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

Categories

Resources