JSON, Servlet and i18n - java

I am working on a back-end project where request is coming as JSON object to my servlet and response is sent as an JSON object as well. I found this LINK useful but need help to understand how filter can be used in my aforementioned back-end scenario to globalized my all classes/APIs through filter
I am new to Java and looking for advice that is it possible? OR I have to manually call ResourceBundle for each class
Thanks in anticipation

If you are receiving your i18n in json payload, you may try doing something as following
// this parses the json
JSONObject jObj = new JSONObject(request.getParameter("yourPramName"));
Iterator it = jObj.keys();
while(it.hasNext())
{
String key = it.next(); // get key
Object o = jObj.get(key); // get value
req.getSession().setAttribute(key, o);
}
Hope this helps.

Related

twitter4j 4.0.2 getRawJSON() returns null

I'm trying to save the tweets I got as JSON objects and however still unable to get the JSON object out of Status objects.
I have checked JSONStoreEnabled() and it's set to true.
API says,
Note that raw JSON forms can be retrieved only from the same thread
invoked the last method call and will become inaccessible once another
method call.
I have my everything inside the main() method, so I guess this shouldn't be an issue.
String tweet = TwitterObjectFactory.getRawJSON( status );
I have checked that the status object contains all the information and it's just that getRawJSON returns null!.
Really appreciate if someone can tell me a fix for this.
I am using this approach in my own app. You can try this while configuring Twitter4j.
Using com.google.gson.Gson;
public Gson gson = new Gson();
ConfigurationBuilder config = new ConfigurationBuilder();
config.setJSONStoreEnabled(true);
config.setOAuthConsumerKey(Keys.TWITTER_KEY);
config.setOAuthConsumerSecret(Keys.TWITTER_SECRET);
config.setOAuthAccessToken(currentSession.getAuthToken().token);
config.setOAuthAccessTokenSecret(currentSession.getAuthToken().secret);
Configuration cf = config.build();
// For Twitter4j
enter code here
String statusJson = TwitterObjectFactory.getRawJSON(status); // status to json
This is it.
Gson gson = new Gson();
String json = gson.toJson( status );
System.out.println( json );
new twitter4j.JSONObject(status)
it is works for me

Decode json object to string android

I used json_encode(); to convert string to json in php and then response it to android but I can't use the response, how can I convert the json to string?
when I display the response it shows this :
"{\n'OK': \n[\n{\n'Name': 'MyName',\n'Gender':'Male'\n}\n]\n}"
what shall I do?
thank you
Since you're just converting a string to json, you're not returning a JSONObject or JSONArray, according to: http://php.net/manual/en/function.json-decode.php
If you must return a string, you may have to use some json library or write your own parser.
If that doesn't sound appealing, I recommending returning a JSONObject or JSONArray with one element.
For example:
php
echo json_encode( array('result' => 'the string you are encoding') );
java
JSONObject json = new JSONObject( encodedStringResponseFromPhp );
String theStringYouEncoded = (String) json.get( "result" );
You'll need to add a throws JSONException to the function you add this java code too or put it inside a try catch block.
Have you tried using a JSON-Library like https://code.google.com/p/json-simple/? Looks like you need some help decoding the string.
Edit: You should use the json2.js library from Douglas Crockford. It provides some extra features and better/older browser support.
Read more...

Consume XML in Java with Jersey

I've build a web application that produces XML code of an object. To my suprise, the xml produced is completely correct and in the format I wanted it. However, I'm now making a method that consumes XML in the same format and turn it back in an object. How can I test if it is working?
I've tried using a REST extension in chrome that posts the exact same XML that my other method produces, but I get the error: "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method." I've also tried putting breakpoints in my code and debugging it that way, but my breakpoints are never even reached.
#GET
#Produces(MediaType.TEXT_XML)
public week_program getXml() {
week_program weekProgram = new week_program();
return weekProgram;
}
#POST
#Consumes(MediaType.TEXT_XML)
public Response PostXml(week_program weekProgram) {
System.out.println(weekProgram);
return Response.status(Status.OK).entity(weekProgram).build();
}
How can I fix it, or even test correctly if it does actually work?
I would suggest using json instead of XML and Gson from Google.
Since json output is usually smaller than XML (fat free).
Object to JSON
DataObject obj = new DataObject();
Gson gson = new Gson();
String json_string = gson.toJson(obj);
JSON to Object
DataObject obj = gson.fromJson(json_string, DataObject.class);
Here's a tutorial. http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

GSON Can I convert only part of JSON, the ones I want Using GSON.fromJSON()

I am working with a big JSON object which has responses form multiple requests.
And the part I am working on requires only few object and they are not always in front.
For Example the json structure is:
**
json = {
mainDocument: {
element1: {
element11: "value11",
element12: {
element121: "value121"
}
},
element2: {
element21: {
element211: {
element2111: "value2111",
element2112: {
element21121: "value21121"
}
}
},
element22: "value22"
}
}
}
**
This structure can change depending on whether or not the request is successful.
Now,
I want to create an java object with the value of element11, element 22, element21121.
Currently I just check the json and use the setters of the object.
I want to know if there is a way to let GSON handle this and not have to parse the json myself.
Thanks in advance for any help you can offer.
I don't know if I understand your question very well, but in order to deserialize a JSON response with Gson, the most proper way in my opinion is to create a class structure that encapsulates the data in the response. In your case something like:
class Response
MainDocument mainDocument
class MainDocument
Element element1
Element element2
class Element
...
If you only need some data from the JSON, you can omit attributes in your class structure and Gson will ignore them. And if an object can have different contents in different responses, you can have something like this:
class Response
MainDocument mainDocument
Error error
And Gson will parse responses both with a root element mainDocument (like the one in the question) or with a root element error... this allows you to adapt your parsing to variable responses...
Obviously, to follow this approach, you need to know all the possible response structures you can have. If your problem is that your JSON response is absolutely variable, and you cannot create a class struture to wrap it, you always could do a manual parsing, somehting like this:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(jsonString).getAsJsonObject();
String element21121 = rootObj
.getAsJsonObject("mainDocument")
.getAsJsonObject("element2")
.getAsJsonObject("element21")
.getAsJsonObject("element211")
.getAsJsonObject("element2112")
.getAsString("element21121");

Parsing JSONObject in javascript or Jquery

Hi friends i have a java.util.Map object in Ajax method like this..
Map<String,List<String>> sm = new TreeMap<>();
List<String> str = new ArrayList<String>();
str.add("val1");
str.add("val2");
str.add("val3");
str.add("val4");
sm.put("shift1", str);
sm.put("shift2", str);
sm.put("shift3", str);
sm.put("shift4", str);
JSONObject json = new JSONObject(sm);
response.getWriter().print(json);
In run time Map elements will be increase or decrease
according to map elements I have to generate table
This is Ajax call.. I don't know how to parse that Map object and dynamically generate the table in javascript.
Please show me how.
I am just answering your question. I don't know java and also i don't understand the details you gave above. If I am wrong, I am sorry and kindly ignore it.
To parse the string to object
In the jQuery, $.parseJSON(string);
In js, JSON.parse(string);
I hope this will help U. Thanks.
var json = $.parseJSON( jsonString );
// This one wouldn't be supported in old browsers
json = JSON.parse( jsonString );
Additionally, you could, in Java, respond with the Content-Type application/json and then in the jQuery AJAX you will receive the JSON already parsed for you.
Of course this will not happen if you specifically configure your jQuery AJAX call to receive an plain text, or HTML, or other content-type response.
For more reference, see here, at the dataType setting.

Categories