Json parsing webservice in struts 2.0? - java

I have used JSONObject json = (JSONObject)new JSONParser().parse(jb.toString()); for getting json object in servlet and JSONObject result=new JSONObject();response.getWriter().write(result.toString()); for posting json object. But i have no idea how to do this in struts 2.0.

You need the Json Plug in. This plug in will be able to parse your action response into a JSON automatically and the interceptors will store your request into your action.
You have an example with Struts2 with annotations and datatables here

String "str" have Json message who extract json in action using key value pair
example to more understanding...
JSONObject json = new JSONObject(str);
rec_id = json.getInt("receptionist_id");
tag_id = json.getInt("tag_id");

Related

Android - Accessing JSON children from a URL

I'm in the process of converting my website to an Android app and one of the pages' data currently is populated via JSON in my website. The way it works is that the URL generates a different JSON data with the same structure based on the passed ID. I already have the logic for passing the ID to the URL. Now I want to read the data through Java code and parse the JSON children and its values in it.
I have a URL that leads to the JSON file in textual form, but I'm not sure how to go about reading the data from it and accessing the child nodes based on the JSON key.
So I guess what I'm asking is what is the usual approach for this procedure? I see a lot of different examples, but none of which are applicable to my problem.
Anyone have any suggestions as to how I should approach this?
JSONObject = new JSONObject(yourjsonstring);
Now you have your Json Object...
If your Json start with array use this:
JSONArray = new JSONArray(yourjsonarray);
You can use existing libraries to parse JSON, gson or Moshi are two solutions.
The way you go about parsing the JSON is as followed
First you need to make pojo's with the same structure as the JSON file.
then you can parse it to java code via the fromJSON() method, this will make new objects and fill it with the data from the JSON.
gson example for clarification:
Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);
where jsonLine = your json file and the Response.Class the pojo in which you want to json to load.
Now you have the JSON values as Java classes in response.
If you're using Retrofit and OkHTTP to perform the network calls i suggest you use Moshi as it's also from Square and claimed to work faster and better than gson. (if you want to know why you can leave a comment).
I think what you're trying to do is this
on post execute method do the following
#Override
protected void onPostExecute(String result) {
String status = "";
String message = "";
String tag = "";
String mail = "";
try {
JSONObject jsonResult = new JSONObject(result);
status = jsonResult.optString("status");
message = jsonResult.optString("message");
tag = jsonResult.optString("tag");
mail = jsonResult.optString("mail");
} catch (JSONException e) {
e.printStackTrace();
}
of course your json array contains different keys
Just reolace them with yours

Inject dynamically generated data into JSON

I have developed a tool that can test some requests to a server, the requests themselves are no more than some simple JSON files that are stored on the disc and can be added continuously, but ... there is one more thing, the JSON files contains an e-mail address that needs to be changed upon running the project each time, this is because each of users have a personal e-mail, I made that because server can't accept more than one request from an user. So I am looking for a solution to inject this e-mail address dynamically into JSON.
I'm using Java for this, and also jayway for REST API and Gson for JSONs. So far I looked into google, but can't find anything at all.
You could do this by these solutions:
Use json file as template string with markup like "{email: ${e-mail}}", then just use jsonTemplate.replace("${e-mail}", email[i])
parse json to Map or Object that model request, then change email field and build again json out of it
Use Gson.
Gson gson = new Gson();
String yourJsonInStringFormat = " {\"email\":placeHolder,\"password\":\"placeHolder\"}";
Map map = gson.fromJson(yourJsonInStringFormat, Map.class);
map.put("email", "jose#com.com");
map.put("password", "123456");
String newJson = gson.toJson(map);
System.out.println(newJson);
This prints out:
{"email":"jose#com.com","password":"123456"}
The fields being injected do not need to be there already. For example this also works:
Gson gson = new Gson();
String yourJsonInStringFormat = "{}";
Map map = gson.fromJson(yourJsonInStringFormat, Map.class);
map.put("email", "jose#com.com");
map.put("password", "123456");
String newJson = gson.toJson(map);
System.out.println(newJson);

GSON to server in url format?

I have converted my java objects to json format.
InetAddress address = InetAddress.getByName("D****");
String ipAddress= address.getHostAddress();
Gson gson = new Gson();
String json = gson.toJson(ipAddress);
System.out.println();
I need to get the json value to server url format, eg: localhost:8080/json
so that I can get that value from the ajax url.
How can I achieve this?
I got it.
I used spring MVC to do this:
Here is the link

Giving incorrect values when converting JSON string to XML and XML back to JSON string

I am using org.json for converting the json string to xml and xml back to json. I am getting the expected response for json string which has only key value pairs, but incase of json string contains of jsonarray objects the return value is different from the input?
Below the code i have used,
import org.json.JSONObject;
import org.json.XML;
String jsonStr ="........";
System.out.println("The JSON Raw Text :"+ jsonStr);
JSONObject jObject = new JSONObject(jsonStr);
String xml = org.json.XML.toString(jObject);
JSONObject xmlJSONObj = XML.toJSONObject(xml);
String jsonConvertString = xmlJSONObj.toString();
System.out.println("JSON text converted : "+jsonConvertString);
What is the error or what is the best way to convert json string to xml and back to json ?
Looks like you are facing problem as explained in this blog.
In short: XML.toString() does NOT produce an XML document. When you use a JSONArray the produced xml string from this method has NO root element.
Therefore, if you are planning to write the contents to an XML file, I'll recommend you use a more stringent API such as org.w3c.dom.*. This will produce a VALID xml document that can be dumped to a file.
Or an easier way would be use something like "<root>" + org.json.XML.toString(jArray) + "</root>" so that you have a root element. This might be parsed pretty well (and as you expect) by XML.toJSONObject().

Simple JSON-String Query

I am developing a web-app using AJAX requests on the client-side and Servlets on the server-side.
My aim is to send objects of Javascript to server, then do some manipulations there and send it back to show here.
Let's say my js object is
var obj={hero:"Spiderman",name:"Peter Parker"};
My Approach
1.Convert obj to JSON string and send
var str= JSON.stringify(obj);
xmlhttp.open("POST",myurl,true);
xmlhttp.setRequestHeader("Content-Type","application/json",true);
xmlhttp.send("data="+str);
2. Recieve string,convert this back to JSON, manipulate "name" to "Bruce Wayne" and send it back as string
3.Recieve and convert back to Json
var data= JSON.parse(xmlhttp.responseText);
I am struggling at second point.I am using org.json for it .I searched and read docs but could not find satisfied answer for converting string to json and vica-versa in JAVA in my context.
It would be really helpful one could provide simple working code or point to some links where I can study.
P.S :
I cannot use Jquery as I am using AngularJS. See Why?
I will always send valid JSON string.
I can use other JSON lib. if its good than org.json and satisfy my needs.
Please provide its jar download link.
Assuming you are able to pull out data in your server code
This is how you can do it using org.json:
JSONParser parser = new JSONParser();
JSONObject requestObj = (JSONObject) parser.parse(data);
String name = (string)requestObj.get("name");
name = "Bruce Wayne";
Code to create the response can look something like this:
JSONObject response = new JSONObject();
response.put("name",name);
return response.toJSONString();
This assumes your server method returns a String type
And in case if you are using Servlet you can use HttpServletResponse object res to create response like:
res.setContentType("application/json");
OutputStream os = res.getOutputStream();
os.write(response.toString().getBytes());
os.close();

Categories

Resources