How to get attributes in Json String in servlet - javascript

How can I get each attribute within a Json String?
I got the Json by converting first my array of objects in JavaScript via JSON.stringify. Afterwards I used ajax to pass the string to my servlet.
Servlet Code:
String data = request.getParameter("jsonData");
System.out.println("json data: " + data);
Result:
[{"courseID":"1","codePI":"PO-BSINSYS-02.01","curriculumID":"3"},
{"courseID":"2","codePI":"PO-BSINSYS-02.02","curriculumID":"3"}]
What I want is to get the individual values of the json so that I can assign them later to my object.
E.g.
ArrayList<Curriculum> arrCur = new ArrayList<>();
for (int x = 0; x < array.size(); x++) {
Curriculum cur = new Curriculum();
cur.setCourseID(courseID[x]);
cur.setCodePO(codePI[x]);
cur.setCurriculumID(curriculumID[x]);
arrCur.add(cur);
}

As "crowder" mentioned, you need to parse the json.
There are several ways to do it.
low-level libraries that would convert your string into a
JSONObject which is sort of a map (with keys "courseID", "codePO"
etc). At the time I used fasterxml but I see a newer approach here:
http://crunchify.com/java-how-to-parse-jsonobject-and-jsonarrays/
Higher-level libraries that would map the json directly into
Java business Objects such as "Curriculum". My own experience was
focused on replacing the simple Servlet with Spring - see for
example https://spring.io/guides/gs/rest-service/
good luck

You can use this way if you are sending arry of object from javascript and if you class -
class Curriculum{
Integer courseID;
String codePI;
Integer curriculumID;
}
Use like this -
String data = request.getParameter("jsonData");
JSONArray jsonArray = new JSONArray(data);
java.lang.reflect.Type curriculumType =new com.google.gson.reflect.TypeToken<List<Curriculum>>(){}.getType();
List<Curriculum> curriculum = new GsonBuilder().create().fromJson(jsonArray.toString(), curriculumType);
This will assign list of Curriculum. Hope this will help you.

You can also use jackson-databind API to convert your json to java object.
Create your bean for Curriculum.
class Curriculum{
Integer courseID;
String codePI;
Integer curriculumID;
public Integer getCourseID() {
return courseID;
}
public void setCourseID(Integer courseID) {
this.courseID = courseID;
}
public String getCodePI() {
return codePI;
}
public void setCodePI(String codePI) {
this.codePI = codePI;
}
public Integer getCurriculumID() {
return curriculumID;
}
public void setCurriculumID(Integer curriculumID) {
this.curriculumID = curriculumID;
}
}
Following is the code to convert your json to Curriculum object
JSONArray jsonArray = getJSONArray();
ObjectMapper objectMapper = new ObjectMapper();
for(int i =0;i<jsonArray.length();i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
//convert json string to object
try {
Curriculum curr= objectMapper.readValue(jsonData.toString().getBytes(), Curriculum.class);
System.out.println(curr);
} catch (Exception e) {
e.printStackTrace();
}
}

Related

How do I convert a C# object into a Javascript array of arrays using JSON?

I'm trying to convert an object of the following C# class type into a Javascript array of arrays:
public class SankeyData
{
public string Source { get; set; }
public int Width { get; set; }
public string Destination { get; set; }
}
The array of arrays in Javascript needs to look like this:
[["Link1",10,"Link2"],["Link3",20,"Link4"],["Link5",30,"Link6"]]
Is there an easy way to do the conversion? I'm using a jQuery $.getJSON to get the data from a C# controller action.
My related technologies include MVC5, jQuery, and JSON. I've tried using JSON.stringify and JSON.parse, but the data won't come over correctly.
Here's what I have so far:
$.getJSON('/Application/Sankey', { id: #Model.ID }, function (data) {
$.each(data, function (i, item) {
sankey.setData(JSON.stringify(item));
});
});
Which gives a close result, but not quite what I need:
[{"Source":"Link1","Width":10,"Destination":"Link2"},{"Source":"Link3","Width":20,"Destination":"Link4"},{"Source":"Link5","Width":30,"Destination":"Link6"}]
NOTE: I'm already using an MVC #model for something else in the page so I can't just set the #model to the SankeyData class.
There is no direct way out there to serialized C# objects to JSON Array. You can achieve this either
By converting C# objects to C# Array and then serialise the array as JSON.
Use Javascript to convert serialised objects to JSON Array.
I would recommend second option as array is heterogeneous.
Something like this:
function objectsToArray(data, columns) {
var dataArray = [];
for (var i in data) {
var itemArray = [];
for (var j in columns) {
itemArray.push(data[i][columns[j]]);
}
dataArray.push(itemArray);
}
return dataArray;
}
data = [{"Source":"Link1","Width":10,"Destination":"Link2"},{"Source":"Link3","Width":20,"Destination":"Link4"},{"Source":"Link5","Width":30,"Destination":"Link6"}]
console.log(objectsToArray(data, ["Source", "Width", "Destination"]));
So, just pull data using $.getJSON and the feed to objectsToArray with key names in order. Hope that solves your problem.

How to pass list of object from JavaScript to Windows Runtime Component C#?

I have created a WinRT component in C# which accepts a IEnumarable as a parameter
C#
public sealed class MyClass
{
public IEnumarable<DtoClass> MyFunction(IEnumarable<DtoClass> properties) {
return properties;
}
}
Java script
var Test=[];
for (var i = 0; i < res1.length; i++)
{
Test.push({ category_id: res1[i].category_id });
}
var Conncetion = WindowsRTSqlite.MyClass();
var result = Conncetion.MyFunction(Test);
I'm returning the same input parameters which I'm sending to MyFunction method but it's not return any result. I am not sure why this is not working. Any Ideas?
Thanks in advance.
How to pass list of object from JavaScript to Windows Runtime Component C#?
Actually the correct way is to serialize the collection to a json string and pass this string to the Windows Runtime Component. And deserialize the json string in the runtime component side for data dealing. After that return back the serialized json string to JavaScript uwp app. For how to serialize in JavaScript please reference this class, for how to serialize in C# you can reference this namespcase. So your code on the JavaScript side may as follows:
var Test = [];
for (var i = 1; i < 6; i++) {
Test.push({ category_id: i });
}
var Conncetion = RuntimeComponent1.MyClass();
var Testserialation = JSON.stringify(Test);
var resultnew = Conncetion.newFunction(Testserialation);
var Testreturn = JSON.parse(resultnew);
And in windows runtime component:
public sealed class MyClass
{
public string NewFunction(string jsonstring)
{
JsonArray entity= JsonArray.Parse(jsonstring);
return entity.ToString();
}
}
I am not sure why this is not working.
According to your code snippet, you created an object array and trying to pass it to the runtime component as IEnumarable<DtoClass>. You passed an array, in my opinion you should be able receive it as an array. And I don't think object can be parsed to DtoClass automatically. If you use a string or int array that can be recognized. For example , an int array:
var newTest = [1, 2, 3, 4];
var result2 = Conncetion.changeArray(newTest);
Code in component:
public int[] ChangeArray([ReadOnlyArray()] int[] input)
{
int[] output =(int[])input.Clone();
// Manipulate the copy.
// ...
return output;
}
More details about passing arrays to a Windows Runtime Component please reference this article.

Array is not serialized and resulting a string

A list that contains a set of arrays is being serialized into jquery. However when check in client side, it is receiving only a string instead of the array object.
c#:
public string jsscript(){
// datatable processing
var arrList = new List<object>();
foreach (DataRow row in table.Rows)
{
string name = row[0].ToString();
string quantity = row[1].ToString();
string balance = row[2].ToString();
string remove = "X";
arrList.Add( new[] { name, quantity, balance, remove });
}
return (new JavaScriptSerializer()).Serialize(arrList);
}
js:
<script>
//dom...
function theDomHasLoaded(e) {
dbdata = <%=jsscripts()%>;
</script>
see JSON string to JS object
you need to use JSON.parse(..) on the serialised string
that is of course presuming that that is the problem... It's not entirely clear what your problem is.

Error deserializing JSON data to Dictionary <string, string>

Here is the JSON that I want to deserialize into Dictionary using native Javascript support.
string data = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}";
But when I attempt to deserialize using below code
Dictionary values = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize>(data);
It gives me an error stating
"Type 'System.String' is not supported for deserialization of an array"
I am using .Net Framework 3.5. Please help me getting this done.
i guess you can not convert that to a dictionary directly... i think deserializer needs a corresponding type, with intelligible property names with type,
i think you can convert to a type, then generate your dictionary, something like:
public class MyClass
{
public List<bool> Symptom { get; set; }
public List<bool> Action { get; set; }
public bool AllArea { get; set; }
public Dictionary<string, List<bool>> getDic()
{
// this is for example, and many many different may be implement
// maybe some `reflection` for add property dynamically or ...
var oDic = new Dictionary<string, List<bool>>();
oDic.Add("Symptom", this.Symptom);
oDic.Add("Action", this.Action);
oDic.Add("AllArea", new List<bool>() { AllArea });
return oDic;
}
}
then:
string data = "{\"Symptom\":[true,true,true],\"Action\":[true,true],\"AllArea\":true}";
System.Web.Script.Serialization.JavaScriptSerializer aa = new System.Web.Script.Serialization.JavaScriptSerializer();
var o = aa.Deserialize<MyClass>(data);
var dic = o.getDic();
anyhow, it was a good question

Get a JSON result based on a Ilist<int> in MVC

I need to build a string like "1-2-3-4-5", from an IList< int > returned by an MVC Action.
Action:
public virtual JsonResult AdvancedSearch(AdAdvancedSearchViewModel asViewModel)
{
IList<int> adIds = new List<int>();
try
{
var asDto = Mapper.Map<AdAdvancedSearchViewModel, AdAdvancedSearchDto>(asViewModel);
adIds = _adService.AdvancedSearch(asDto);
}
catch
{
adIds = null;
}
return Json(adIds);
}
Javascript function that processes the result:
function onAdAdvancedSearchSuccess(jsonAdListIds)
{
$("#adAdvancedSearchListForm #ids").val(jsonAdListIds);
}
The problem is that I get a string like this "[1,2,3,4]" in the "#adAdvancedSearchListForm #ids" HTML input, and I need to get "1-2-3-4", any idea?
Thanks.
If you want to do it at the client side, simply iterate throught the result array and build the string you want.
$.getJSON("yourURL", { Name: "John", Loc: "2pm" },function(result){
var str="";
$.each(result,function(i,item){
str=str+"-"+item;
});
alert(str);
});
Assuming Name and Loc are the properties of your viewmodel.
If you want to do it on the server side, you may use String.Join method to build the string representation you want. You may need to update the return type of your action method.
public string AdvancedSearch(AdAdvancedSearchViewModel asViewModel)
{
List<int> adIds = new List<int>();
//fill the list
var resutlStr= String.Join("-",adIds.ToArray());
return resutlStr;
}
I prefer to keep my action method returns JSON result instead of this string represetnation because an action method which returns JSON can be used in many places compared to this concrete string return implementation.
AJAX is returning an array which is expected since you are converting a list.
Try parsing the array into the string:
var r = jsonAdListIds[0];
for (var i = 1; i < jsonAdListIds.length; i++) {
r += '-' + jsonAdListIds[i];
}

Categories