How read data sent by Client with Spark? - javascript

I have to read some data sent by Client using Spark (a framework for Java).
This is the code of client's post request. I am using jQuery.
$.post("/insertElement",
{item:item.value, value: value.value, dimension: dimension.value });
The code of server:
post(new Route("/insertElement") {
#Override
public Object handle(Request request, Response response) {
String item = (String) request.attribute("item");
String value = (String) request.attribute("value");
String dimension = (String) request.attribute("dimension");
Element e = new Element(item, value, dimension);
ElementDAO edao = new ElementDAO();
edao.insert(e);
JSONObject json = JSONObject.fromObject( e );
return json;
}
});
I am using Spark so I only have to define the route.
I would like to store in a database the data sent by client, but all the attributes are null.
I think that this way isn't correct. How can I read the sent data?

They way you send your data, using HTTP POST, you're posting the JSON as request body, not as request attributes. This means you shouldn't use request.attribute("item") and the others, but instead parse the request body to a Java object. You can use that object to create the element and store it using the DAO.

You will need something like this:
post(new Route("/insertElement") {
#Override
public Object handle(Request request, Response response) {
String body = request.body();
Element element = fromJson(body, Element.class);
ElementDAO edao = new ElementDAO();
edao.insert(e);
JSONObject json = JSONObject.fromObject( e );
return json;
}
});
public class Element {
private String item;
private String value;
private String dimension;
//constructor, getters and setters
}
public class JsonTransformer {
public static String toJson(Object object) {
return new Gson().toJson(object);
}
public static <T extends Object> T fromJson(String json, Class<T> classe) {
return new Gson().fromJson(json, classe);
}
}

try using request.queryParams("item") and so on.

Assuming this is the JSON I'm sending in my request
{ 'name': 'Rango' }
This is how I've configured my Controller to parse request body.
public class GreetingsController {
GreetingsController() {
post("/hello", ((req, res) -> {
Map<String, String> map = JsonUtil.parse(req.body());
return "Hello " + map.get("name") + "!";
})));
}
}
public class JsonUtil {
public static Map<String, String> parse(String object) {
return new Gson().fromJson(object, Map.class);
}

Related

Spring Boot Post API returns null values

I've been playing around with Spring MVC and came across an issue, where I send a JSON object from the frontend with JavaScript to the backend. To do so, I use a POST Method, which seems to return null values on the backend.
JavaScript:
function calcBudget() {
var table = document.getElementById("mainTable");
const jsonBody = [];
for (var i = 1; i < table.rows.length; i++) {
const jsonItem = {};
jsonItem ["name"] = table.rows[i].cells[0].firstChild.value;
jsonItem ["category"] = table.rows[i].cells[1].firstChild.value;
jsonItem ["amount"] = table.rows[i].cells[2].firstChild.value;
jsonBody.push(jsonItem);
}
console.log(JSON.stringify(jsonBody));
var xhr = new XMLHttpRequest();
xhr.open("POST", "/home/test", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
jsonBody
}));
}
JavaScript Output:
[{"name":"01","category":"01","amount":"03"}]
RestController:
#Controller
public class GreetingsController {
#PostMapping("/home/test")
public String readInput(#RequestBody CalcModel model) {
System.out.println(model.expenseName +" " + model.expenseCategory+" "+ model.expenseAmount);
return "index";
}
}
RestController Output:
null null null
CalcModel:
public class CalcModel {
public String expenseName;
public String expenseCategory;
public Double expenseAmount;
public CalcModel(String expenseName, String expenseCategory, Double expenseAmount) {
this.expenseName = expenseName;
this.expenseCategory = expenseCategory;
this.expenseAmount = expenseAmount;
}
}
Why is the RestController output null? I have attempted to integrate an H2 database, as I assumed I would need one. Turned out, though, that this does not work either. I also tried to use getters for the CalcModel, without any luck. Any ideas?
Edit:
It seems as I'm sending a JSON array to Spring Boot, which expects to find just a single object, not an array of objects. Removing the square brackets seems to solve the issue when testing via Postman. Now I need to find a solution how to make SpringBoot recognize the response body as a JSON array.
Solution:
Change RestController Method to this (Request Body needs to be an ArrayList)
#PostMapping("/home/test")
public String readInput(#RequestBody ArrayList<CalcModel> model) {
for (CalcModel calcModel : model) {
System.out.println(calcModel.name + " " + calcModel.category + " " + calcModel.amount);
}
return "index";
}
In the JavaScript file, remove the curly brackets
xhr.send(JSON.stringify(jsonBody));
It seems like you have different namings in the jsonBody and the CalcModel. Try changing the names to the same thing.
[{"name":"01","category":"01","amount":"03"}]
public class CalcModel {
public String name;
public String category;
public Double amount;
You might also need a parameterless constructor and getters and setters.

Create JSON Object Using ASP.NET [duplicate]

I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the JSON string and them format your response as JSON?
Using Newtonsoft.Json makes it really easier:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
Documentation: Serializing and Deserializing JSON
You could use the JavaScriptSerializer class, check this article to build an useful extension method.
Code from article:
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
Usage:
using ExtensionMethods;
...
List<Person> people = new List<Person>{
new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
};
string jsonString = people.ToJSON();
Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.
//Create my object
var myData = new
{
Host = #"sftp.myhost.gr",
UserName = "my_username",
Password = "my_password",
SourceDir = "/export/zip/mypath/",
FileName = "my_file.zip"
};
//Tranform it to Json object
string jsonData = JsonConvert.SerializeObject(myData);
//Print the Json object
Console.WriteLine(jsonData);
//Parse the json object
JObject jsonObject = JObject.Parse(jsonData);
//Print the parsed Json object
Console.WriteLine((string)jsonObject["Host"]);
Console.WriteLine((string)jsonObject["UserName"]);
Console.WriteLine((string)jsonObject["Password"]);
Console.WriteLine((string)jsonObject["SourceDir"]);
Console.WriteLine((string)jsonObject["FileName"]);
This library is very good for JSON from C#
http://james.newtonking.com/pages/json-net.aspx
This code snippet uses the DataContractJsonSerializer from System.Runtime.Serialization.Json in .NET 3.5.
public static string ToJson<T>(/* this */ T value, Encoding encoding)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
{
serializer.WriteObject(writer, value);
}
return encoding.GetString(stream.ToArray());
}
}
If you need complex result (embedded) create your own structure:
class templateRequest
{
public String[] registration_ids;
public Data data;
public class Data
{
public String message;
public String tickerText;
public String contentTitle;
public Data(String message, String tickerText, string contentTitle)
{
this.message = message;
this.tickerText = tickerText;
this.contentTitle = contentTitle;
}
};
}
and then you can obtain JSON string with calling
List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");
string json = new JavaScriptSerializer().Serialize(request);
The result will be like this:
json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"
Hope it helps!
You can also try my ServiceStack JsonSerializer it's the fastest .NET JSON serializer at the moment. It supports serializing DataContracts, any POCO Type, Interfaces, Late-bound objects including anonymous types, etc.
Basic Example
var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = JsonSerializer.SerializeToString(customer);
var fromJson = JsonSerializer.DeserializeFromString<Customer>(json);
Note: Only use Microsofts JavaScriptSerializer if performance is not important to you as I've had to leave it out of my benchmarks since its up to 40x-100x slower than the other JSON serializers.
Take a look at http://www.codeplex.com/json/ for the json-net.aspx project. Why re-invent the wheel?
If you want to avoid creating a class and create JSON then Create a dynamic Object and Serialize Object.
dynamic data = new ExpandoObject();
data.name = "kushal";
data.isActive = true;
// convert to JSON
string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
Read the JSON and deserialize like this:
// convert back to Object
dynamic output = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
// read a particular value:
output.name.Value
ExpandoObject is from System.Dynamic namespace.
If you can't or don't want to use the two built-in JSON serializers (JavaScriptSerializer and DataContractJsonSerializer) you can try the JsonExSerializer library - I use it in a number of projects and works quite well.
If you're trying to create a web service to serve data over JSON to a web page, consider using the ASP.NET Ajax toolkit:
http://www.asp.net/learn/ajax/tutorial-05-cs.aspx
It will automatically convert your objects served over a webservice to json, and create the proxy class that you can use to connect to it.
Encode Usage
Simple object to JSON Array EncodeJsObjectArray()
public class dummyObject
{
public string fake { get; set; }
public int id { get; set; }
public dummyObject()
{
fake = "dummy";
id = 5;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
sb.Append(id);
sb.Append(',');
sb.Append(JSONEncoders.EncodeJsString(fake));
sb.Append(']');
return sb.ToString();
}
}
dummyObject[] dummys = new dummyObject[2];
dummys[0] = new dummyObject();
dummys[1] = new dummyObject();
dummys[0].fake = "mike";
dummys[0].id = 29;
string result = JSONEncoders.EncodeJsObjectArray(dummys);
Result:
[[29,"mike"],[5,"dummy"]]
Pretty Usage
Pretty print JSON Array PrettyPrintJson() string extension method
string input = "[14,4,[14,\"data\"],[[5,\"10.186.122.15\"],[6,\"10.186.122.16\"]]]";
string result = input.PrettyPrintJson();
Results is:
[
14,
4,
[
14,
"data"
],
[
[
5,
"10.186.122.15"
],
[
6,
"10.186.122.16"
]
]
]
The DataContractJSONSerializer will do everything for you with the same easy as the XMLSerializer. Its trivial to use this in a web app. If you are using WCF, you can specify its use with an attribute. The DataContractSerializer family is also very fast.
I've found that you don't need the serializer at all. If you return the object as a List.
Let me use an example.
In our asmx we get the data using the variable we passed along
// return data
[WebMethod(CacheDuration = 180)]
public List<latlon> GetData(int id)
{
var data = from p in db.property
where p.id == id
select new latlon
{
lat = p.lat,
lon = p.lon
};
return data.ToList();
}
public class latlon
{
public string lat { get; set; }
public string lon { get; set; }
}
Then using jquery we access the service, passing along that variable.
// get latlon
function getlatlon(propertyid) {
var mydata;
$.ajax({
url: "getData.asmx/GetLatLon",
type: "POST",
data: "{'id': '" + propertyid + "'}",
async: false,
contentType: "application/json;",
dataType: "json",
success: function (data, textStatus, jqXHR) { //
mydata = data;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log(xmlHttpRequest.responseText);
console.log(textStatus);
console.log(errorThrown);
}
});
return mydata;
}
// call the function with your data
latlondata = getlatlon(id);
And we get our response.
{"d":[{"__type":"MapData+latlon","lat":"40.7031420","lon":"-80.6047970}]}
Include:
using System.Text.Json;
Then serialize your object_to_serialize like this:
JsonSerializer.Serialize(object_to_serialize)

How to return a json array with struts?

Here is my struts action
#Action("/trylogin")
#ParentPackage("json-default")
#Result(type = "json", params = { "includeProperties", "msg, productsList" })
public class Login extends ActionSupport {
private static final long serialVersionUID = 1L;
private String utilisateur;
private String motdepasse;
private String msg;
private ArrayList<Article> productsList = new ArrayList<Article>();
#Autowired
private Dao dao;
public String execute() {
if (dao.validCredentials(utilisateur, motdepasse)) {
System.out.println("USER FOUND");
productsList = dao.fetchProducts();
msg = "success";
} else {
System.out.println("ERREUR");
msg = "error";
}
return ActionSupport.SUCCESS;
}
public ArrayList<Article> getProductsList() {
return productsList;
}
public String getMsg() {
return msg;
}
Here is my ajax post :
$.post({
url: "trylogin",
data: {
utilisateur: name,
motdepasse: password
}
}).done(function(data) {
console.log(data.productsList.length);
}).fail(function( jqXHR, textStatus ) {
console.log("Fail");
})
I'd like to fetch my productsList. In my Action the list is loaded properly. But once I console.log(data.productsList) it's empty.
How should I do to get the productsList from my struts action to my javascript ?
My productsList is a list of objects that has various attributes like name/id/color...
The parameter includeProperties is a list of regex expressions. When you use a parameter productsList the json serializer only finds this property, but when goes further and parse it's elements none of them are included. If you use this parameter with the result only properties that match the expressions are included in the json output.
You need to configure includeProperties in the json result. For example
#Result(type="json", params = {"includeProperties", "msg,
productsList\\[\\d+\\]\\.id,productsList\\[\\d+\\]\\.name,productsList\\[\\d+\\]\\.color"})
Note, that special characters are double escaped.
You need to list each attribute of Article in the whitelist of the allowed properties.
Let's say Article has id, name and color attributes, the configuration would be:
#Result(type = "json", params = { "includeProperties",
"msg,
productsList\\[\\d+\\]\\.id,
productsList\\[\\d+\\]\\.name,
productsList\\[\\d+\\]\\.color"})
This is why I prefer to use a root object instead of includeProperties, even if in your case you'd need to figure out a way to deal with msg (that could be probably be composed client side based on the result of the List, though).

How to pass json data from C# controller to angular js?

How to pass json data from C# controller to angular js ? I want to pass json from controller to angular js. I tried different but none of them worked. See my code below,
var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
$http.get("/adnActions/getJson")
.success(function (response) { alert(response.records); $scope.names = response.records; });
});
C# controller code
public async Task<string> getJson()
{
data="{'records':[ {'Name':'Alfreds Futterkiste','City':'Berlin','Country':'Germany'}, {'Name':'Ana Trujillo Emparedados y helados','City':'México D.F.','Country':'Mexico'}]}";
return data;
}
but am unable to get the data in angular js controller
below is the error raised in console,
"Error: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
how to fix this? Whats the problem here?
I suspect it is because the format of your JSON. You are using single quotes vs double. Valid JSON uses double quotes.
Here is what i get when i run your json i have changed the response to be HttpResponseMessage and explicitly set the response content type to eliminate this as an issue. Based on your error being on Javascript side i think your problem is your single quotes in your JSON.
public async Task<HttpResponseMessage> GetJsonSingle()
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("{'records':[ {'Name':'Alfreds Futterkiste','City':'Berlin','Country':'Germany'}, {'Name':'Ana Trujillo Emparedados y helados','City':'México D.F.','Country':'Mexico'}]}")
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return result;
}
results in:
While double quotes:
public async Task<HttpResponseMessage> GetJsonDouble()
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("{\"records\":[ {\"Name\":\"Alfreds Futterkiste\",\"City\":\"Berlin\",\"Country\":\"Germany\"}, {\"Name\":\"Ana Trujillo Emparedados y helados\",\"City\":\"México D.F.\",\"Country\":\"Mexico\"}]}")
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return result;
}
works correctly:
use EF to create json object and use web api controller to GET(select),PUT(update),POST(insert),DELETE(delete) data
public class CarsController : ApiController
{
private static readonly ICarRepository _cars = new CarRepository();
// GET api/<controller>
public IEnumerable<Car> Get()
{
return _cars.GetAllCars();
}
// GET api/<controller>/5
public Car Get(int id)
{
Car c = _cars.GetCar(id);
if (c == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
return c;
}
// POST api/<controller>
public Car Post(Car car)
{
return _cars.AddCar(car);
}
// PUT api/<controller>/5
public Car Put(Car car)
{
if (!_cars.Update(car))
throw new HttpResponseException(HttpStatusCode.NotFound);
return car;
}
// DELETE api/<controller>/5
public Car Delete(int id)
{
Car c = _cars.GetCar(id);
_cars.Remove(id);
return c;
}
}
}

SPRING --- How to submit an array of object to controller

As title,
i using angularjs to submit
my spring controller:
#RequestParam(value = "hashtag[]") hashtag[] o
above are work for array parameter but not an array object
my js script:
$http({
method: 'POST',
url: url,
data: $.param({
hashtag : [{label:"success",value:"ok"},{label:"success",value:"ok"},{label:"success",value:"ok"}],
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
i observe from chrome, the form data is
hashtag[0][label]:success
hashtag[0][value]:10
hashtag[1][label]:success
hashtag[2][value]:10
hashtag[3][label]:success
hashtag[3][value]:10
But the Spring show me
org.springframework.web.bind.MissingServletRequestParameterException: Required hashtag[] parameter 'id[]' is not present
Previously i was able to receive an array of parameters, but not an object. so can someone enlighten me?
Try #RequestParam(value = "hashtag") hashtag[] o
Given that you have a class named hashtag havinf label and value attributes.
Try Using #ModelAttribute
Create a new Java class HashtagList like given below
public class HashTagList {
private List<HashTag> hashTag;
public List<HashTag> getHashTag() {
return hashTag;
}
public void setHashTag(List<HashTag> hashTag) {
this.hashTag = hashTag;
}
}
and in your controller method
#ModelAttribute("hashtag") HashTagList hashTagList
Is the java class name hashtag or HashTag ?
Because it is a POST request you can use #RequestBody annotation and create a DTO class to map the data you are sending or maybe even use your domain object.
For example, why not create reusable POJO class that can hold key->value pairs like:
#JsonPropertyOrder({"label", "value"})
public final class Pair<K,V> implements Map.Entry<K,V>, Serializable {
private final K key;
private final V value;
#JsonCreator
public Pair(#JsonProperty("label")K key, #JsonProperty("value")V value) {
this.key = key;
this.value = value;
}
// ... rest of the implementation
}
Note: I have assumed here you are using Jackson mapper, hence the JSON annotations.
Next step is to get the class that will hold the data structure you are sending from your client:
public class HashTags implements Serializable {
List<Pair<String, String>> hashtag = new ArrayList<>();
// ... rest of the implementation
}
Then in your controller you will have to do something like:
#RequestBody HashTags entity

Categories