With the below code I have converted list to json but the format is as
follows:
{"GodownMaster":[{"pname":"FCI CHARLAPALLI","pcode":"16042"},
{"pname":"MLS CIRCLE 1 L.B. NAGAR","pcode":"16016"},{"pname":"MLS CIRCLE 4
AZAMABAD","pcode":"16003"},{"pname":"MLS CIRCLE 6
VIDYANAGAR","pcode":"16005"},{"pname":"OTHERS","pcode":"1699"}]}
but I want to convert it as :
[{"pname":"FCI CHARLAPALLI","pcode":"16042"},
{"pname":"MLS CIRCLE 1 L.B. NAGAR","pcode":"16016"},{"pname":"MLS CIRCLE 4
AZAMABAD","pcode":"16003"},{"pname":"MLS CIRCLE 6
VIDYANAGAR","pcode":"16005"},{"pname":"OTHERS","pcode":"1699"}]
Below is my spring controller :
#RequestMapping("/getGodowns")
public #ResponseBody Map
getGodownsBasedOnDistrict(#RequestParam(value="district_code") String
dist_code) {
List<CscGodownBean> godown_list = null;
Map<String, List<CscGodownBean>> m = new HashMap();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}
if(godown_list!=null) {
for(int i=0;i<godown_list.size();i++) {
m.put("GodownMaster",godown_list);
}
}
return m;
}
Why are you putting your list into Map? Code looks weird. If you want to return a list, just do it:
#RequestMapping("/getGodowns")
public #ResponseBody List<CscGodownBean> getGodownsBasedOnDistrict(#RequestParam(value="district_code") String dist_code) {
List<CscGodownBean> godown_list = null;
String exception = null;
try {
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
} catch (Exception ex) {
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list;
}
Change the return result from Map to List<CscGodownBean> and put : retrun godown_list
So;
#RequestMapping("/getGodowns")
public #ResponseBody List<CscGodownBean>
getGodownsBasedOnDistrict(#RequestParam(value="district_code") String
dist_code) {
List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}
return godown_list ;
}
UPDATE
And you can return result as string and you will get what you need :
#RequestMapping("/getGodowns")
public #ResponseBody String
getGodownsBasedOnDistrict(#RequestParam(value="district_code") String
dist_code) {
List<CscGodownBean> godown_list = new ArrayList<CscGodownBean>();
String exception = null;
try
{
//getting name and codes here
godown_list = scm_service.getGodownListBesedOnDistCode(dist_code);
}catch(Exception ex)
{
ex.printStackTrace();
exception = ex.getMessage();
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String arrayToJson = objectMapper.writeValueAsString(godown_list);
System.out.println("Convert List to JSON :");
System.out.println(arrayToJson);
return arrayToJson ;
}
The returned String is json format.
Here is what I have used:
#RequestMapping("/alluserreportJSON")
public #ResponseBody String getusersJSON() {
ObjectMapper objectMapper = new ObjectMapper();
//Set pretty printing of json
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
List<AppUser> userlist = null;
#SuppressWarnings("unused")
String exception = null;
String arrayToJson = null;
try {
userlist = userService.findAllUsers();
arrayToJson = objectMapper.writeValueAsString(userlist);
} catch (Exception ex) {
ex.printStackTrace();
exception = ex.getMessage();
}
return arrayToJson;
}
Hope it helps someone. You can see it working here.
You add return type as Map, still you want the same then Just in ajaxComplete() put code;
var response = '{"GodownMaster":[{"pname":"FCI CHARLAPALLI","pcode":"16042"}, {"pname":"MLS CIRCLE 1 L.B. NAGAR","pcode":"16016"},{"pname":"MLS CIRCLE 4 AZAMABAD","pcode":"16003"},{"pname":"MLS CIRCLE 6 VIDYANAGAR","pcode":"16005"},{"pname":"OTHERS","pcode":"1699"}]}'
JSON.stringify(JSON.parse(response).GodownMaster);
Related
Environment
.net 7
Using Both System.Text.Json
Also NewtonSoft.Json ( 13.0.2)
Example code
string str = #"{
""DateTimeNull"":""""
}";
try
{
var t = System.Text.Json.JsonSerializer.Deserialize<Test>(str);
}
catch (JsonException ex)
{
Console.WriteLine(new { Field = ex.Path , Message = ex.Message });
}
try
{
var t = Newtonsoft.Json.JsonConvert.DeserializeObject<Test>(str);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
public class Test
{
public DateTime? DateTimeNull { get; set; }
}
In above System.Text.Json Deserlizer throw exception but newtonsoft.json line is not throwing any exception. It is converting empty value to null but I want it should thow error and due to limitation I can not move to System.Text.Json as of now.
Payload ( This is i already set in str)
Sample one
#"{
""DateTimeNull"":""""
}";
Expected result: Throw error and should not convert to null.
Sample two.
#"{
""DateTimeNull"": null
}";
Expected result: Should not throw error and it is null value and destination type is null.
I usually recommend to use a JsonConstructor:
var json = #"{
""DateTimeNull"":""""
}";
Test test = JsonConvert.DeserializeObject<Test>(json);
public class Test
{
public DateTime? DateTimeNull { get; set; }
[Newtonsoft.Json.JsonConstructor]
public Test(JToken DateTimeNull)
{
if (DateTimeNull.Type == JTokenType.Null) this.DateTimeNull = null;
else if ((string)DateTimeNull == string.Empty)
throw new JsonException("DateTimeNull property should not be an empty string");
else this.DateTimeNull = DateTimeNull.ToObject<DateTime>();
}
}
I have this code,
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(strJson); //works fine here
return strJson; //return it doesn't display pretty on browser
Any idea how to fix this? I've been trying all the solution here on the internet and especially stackoverflow and none of it works.
If you want clear view, it's from my previous code
I use thymeleaf html again,
#Controller
#RequestMapping("/menu")
public class DataController {
// load json
private List<DataModel> theDatawiz;
private String strJson = null;
#PostConstruct
private void loadData() {
// load json
ClassPathResource classPathResource = new ClassPathResource("json/data.json");
try {
byte[] binaryData = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
strJson = new String(binaryData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
// setup array mapper
ObjectMapper objectMapper = new ObjectMapper();
DataModel[] datawiz = null;
try {
datawiz = objectMapper.readValue(strJson, DataModel[].class);
} catch (Exception e) {
e.printStackTrace();
}
// create the list
theDatawiz = new ArrayList<>();
for(int i = 0; i < datawiz.length; i++) {
DataModel dat = new DataModel(datawiz[i].getId(),datawiz[i].getName());
theDatawiz.add(dat);
}
}
// add mapping for "/list"
#GetMapping("/list")
public String listMenu(Model theModel) {
// add to the spring model
theModel.addAttribute("thelist", theDatawiz);
return "menu-list";
}
// add mapping for "/list"
#GetMapping("/jason")
public String printJson(Model theModel) {
// add to the spring model
theModel.addAttribute("result", strJson);
return "jason";
}
}
On the jason.html,
<p th:text="'JSON: ' + ${result}" style="white-space: pre"></p>
What could be the reason of this error in the code below?
loginButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v){
final String e_mail = e_mailEditText.getText().toString();
final String password = passwordEditText.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
// int age = jsonResponse.getInt("age");
Intent intent = new Intent(login.this, Welcome.class);
intent.putExtra("name", name);
// intent.putExtra("age", age);
intent.putExtra("e_mail", e_mail);
login.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(e_mail, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(login.this);
queue.add(loginRequest);
}
});
Check if you have the key first:
if (jsonObject.has("name")) {
String name = jsonObject.getString("name");
}
For others users which have the org.json.JSONException: No value for //your parameter.
In this case you should check if the name is empty.
For example using method jsonResponse.optString("name").
Live example:
if (success) {
String name = jsonResponse.optString("name"); //will get name value or return empty String
if (!name.equals("")) {
//Your code if name is exist
Intent intent = new Intent(login.this, Welcome.class);
intent.putExtra("name", name);
intent.putExtra("e_mail", e_mail);
login.this.startActivity(intent);
} else {
//Your code if the name is empty
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
Can't say for sure without knowing the context (or the line number of the exception), but my money would be on the call:
jsonResponse.getString("name")
Most likely, the JSON received from the server doesn't contain any name/value pairs with name name.
Can we return JSON object from spring controller and write that JSON object on jsp page.
Below is my jsp page:
<script type="text/javascript">
dojo.require("dojox.grid.EnhancedGrid");
dojo.require("dojox.data.QueryReadStore");
dojo.ready(function(){
mystore=new dojo.data.ItemFileReadStore({url:"<%=request.getContextPath()%>/showData.htm"});
var layout= [
{field: 'ID', name: 'SID',formatter: hrefFormatter,datatype:"number" },
{field: 'SPREAD',name: 'SPREAD',autoComplete: true}
]
var grid = new dojox.grid.EnhancedGrid({
id: 'myGrid',
----
});
</script>
Controller:
#RequestMapping(value = "/showData", method = RequestMethod.GET)
public void getSTIDData(HttpServletRequest request,
HttpServletResponse response, #ModelAttribute VINDTO vinData,
BindingResult beException) throws IOException {
try {
......
......
XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.alias("items", com.loans.auto.DTO.VINRequestDTO.class);
String str = xstream.toXML(vinListCopy);
StringBuffer rowData = new StringBuffer();
rowData.append("{'numRows':").append(vinListCopy.size())
.append(",'items':").append(str).append("}");
PrintWriter out = response.getWriter();
out.print(rowData);
}
Instead of getSTIDData(..) returning void , i want this method to return ModelAndView object, but when i return ModelAndView object, in jsp page data is not getting loaded and it says "NO Data Found". Please suggest. Thanks.
Below is the exception generated when i used Gson
SyntaxError {stack: "SyntaxError: Unexpected identifier↵ at Object.d… at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)", message: "Unexpected identifier"}
message: "Unexpected identifier"
stack: "SyntaxError: Unexpected identifier↵ at Object.dojo.fromJson (/MYWebProject/dojo/_base/json.js:26:23)↵ at Object.dojo._contentHandlers.dojo.contentHandlers.json (/MYWebProject/dojo/_base/xhr.js:78:16)↵ at Object.dojo._contentHandlers.dojo.contentHandlers.json-comment-optional (/MYWebProject/dojo/_base/xhr.js:156:28)↵ at _deferredOk (/MYWebProject/dojo/_base/xhr.js:432:42)↵ at notify (/MYWebProject/dojo/_base/Deferred.js:187:23)↵ at complete (/MYWebProject/dojo/_base/Deferred.js:168:4)↵ at resolve.callback (/MYWebProject/dojo/_base/Deferred.js:248:4)↵ at eval (/MYWebProject/dojo/_base/xhr.js:627:8)↵ at signalListener (/MYWebProject/dojo/Deferred.js:37:21)↵ at signalWaiting (/MYWebProject/dojo/Deferred.js:28:4)"
__proto__: Error
yes you can return as JSON response.showing with the help of Gson API
#RequestMapping(value = "/showData", method = RequestMethod.GET)
public #ResponseBody String getUserHomePage(HttpServletRequest request,HttpServletResponse response, #ModelAttribute VINDTO vinData,BindingResult beException) throws IOException {
//you code stuff to create model object bean
Gson gson = new Gson();
return gson.toJson(objectBean);
}
Keep it clean and simple...
Here is a real life snippet of code ...
#RequestMapping(value = "/actions/getImplGroups", method = RequestMethod.POST)
public ResponseEntity<String> getImplGroups(HttpServletRequest request, HttpServletResponse response) {
List<String> groups = bpmClient.getAllGroups();
ObjectMapper mapper = new ObjectMapper();
String jsonString;
try {
jsonString = mapper.writeValueAsString(groups);
} catch (JsonGenerationException e) {
jsonString = "Error with json generation: " + e.getMessage();
} catch (JsonMappingException e) {
jsonString = "Error with json mapping: " + e.getMessage();
} catch (IOException e) {
jsonString = "Error with json: " + e.getMessage();
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(jsonString, responseHeaders, HttpStatus.CREATED);
}
The important point to consider is sending the correct web header, so that your page expects to see json.
I the case above we used the Jackson library to create the json, but in truth you could format the json any way you like. Here is an example of a simple, manually formatted string...
#RequestMapping(value = "/actions/getTicketsNotUpdatedWithinShift", method = RequestMethod.POST)
public ResponseEntity<String> getTicketsNotUpdatedWithinShift(String center, String sections, String minutesInShift, Model model) {
String[] sectionArray = sections.split(",");
String json = "";
String rowsString = "";
for (String section : sectionArray) {
List<Map<String, String>> rows = service.getMinutesSinceLastTicketUpdate(center, section);
for (Map<String, String> row : rows) {
int minutesSinceUpdate = Integer.parseInt(row.get("minutes"));
if (minutesSinceUpdate > Integer.parseInt(minutesInShift)) {
String description = row.get("description");
rowsString = rowsString + "\"" + description + "\",";
}
}
}
// Build the json structure
if (!rowsString.isEmpty()) {
// Trim the trailing comma.
rowsString = rowsString.replaceAll(",$", "");
json = "[" + rowsString + "]";
} else {
json = "[]";
}
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}
I'm working on an application that needs to get the source of a web page from a link, and then parse the html from that page.
Could you give me some examples, or starting points where to look to start writing such an app?
You can use HttpClient to perform an HTTP GET and retrieve the HTML response, something like this:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
I would suggest jsoup.
According to their website:
Fetch the Wikipedia homepage, parse it to a DOM, and select the headlines from the In the news section into a list of Elements (online sample):
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Elements newsHeadlines = doc.select("#mp-itn b a");
Getting started:
Download the jsoup jar core library
Read the cookbook introduction
This question is a bit old, but I figured I should post my answer now that DefaultHttpClient, HttpGet, etc. are deprecated. This function should get and return HTML, given a URL.
public static String getHtml(String url) throws IOException {
// Build and set timeout values for the request.
URLConnection connection = (new URL(url)).openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
// Read and store the result line by line then return the entire string.
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder html = new StringBuilder();
for (String line; (line = reader.readLine()) != null; ) {
html.append(line);
}
in.close();
return html.toString();
}
public class RetrieveSiteData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
StringBuilder builder = new StringBuilder(100000);
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
builder.append(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return builder.toString();
}
#Override
protected void onPostExecute(String result) {
}
}
Call it like
new RetrieveFeedTask(new OnTaskFinished()
{
#Override
public void onFeedRetrieved(String feeds)
{
//do whatever you want to do with the feeds
}
}).execute("http://enterurlhere.com");
RetrieveFeedTask.class
class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
String HTML_response= "";
OnTaskFinished onOurTaskFinished;
public RetrieveFeedTask(OnTaskFinished onTaskFinished)
{
onOurTaskFinished = onTaskFinished;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]); // enter your url here which to download
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null)
{
// System.out.println(inputLine);
HTML_response += inputLine;
}
br.close();
System.out.println("Done");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return HTML_response;
}
#Override
protected void onPostExecute(String feed)
{
onOurTaskFinished.onFeedRetrieved(feed);
}
}
OnTaskFinished.java
public interface OnTaskFinished
{
public void onFeedRetrieved(String feeds);
}
If you have a look here or here, you will see that you can't do that directly with android API, you need an external librairy...
You can choose between the 2 here's hereabove if you need an external librairy.
One of the other SO post answer helped me. This doesn't read line by line; supposingly the html file had a line null in between. As preRequisite add this dependancy from project settings "com.koushikdutta.ion:ion:2.2.1" implement this code in AsyncTASK. If you want the returned -something- to be in UI thread, pass it to a mutual interface.
Ion.with(getApplicationContext()).
load("https://google.com/hashbrowns")
.asString()
.setCallback(new FutureCallback<String>()
{
#Override
public void onCompleted(Exception e, String result) {
//int s = result.lastIndexOf("user_id")+9;
// String st = result.substring(s,s+5);
// Log.e("USERID",st); //something
}
});
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null)
{
// System.out.println(inputLine);
result += inputLine;
}
br.close();
return result;
} catch (Exception e) {
e.printStackTrace();
return "failed";
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("https://www.example.com").get();
}catch (Exception e){
e.printStackTrace();
}
Log.i("Result", result);
}