Getting inappropriate output converting object to string - javascript

I want to extract data from object but getting inappropriate output.
I am passing Id that is 11 from ajax post in the form of json.stringify.
[WebMethod]
public static int GetData(object ID)
{
string a = ID.ToString(); // Getting:`System.Object[]` instead of my id `11`
}
console.log(Params)//FILE_ID[0]=11
console.log(Params['FILE_ID']);//11
$.ajax({
data: JSON.stringify({ FileID: Params['FILE_ID'] }),
});
How to get just id from object?

Instead of below code
string a = ID.ToString(); // Getting:`System.Object[]` instead of my id `11`
use this code and see whether you can get the ID
string a = ID["FileID"];
or
string a = ID["FileID"].ToString();
Hope this helps you.

Related

add a property to a Json array with Gson

I am serializing a list of objects with Gson like this:
String responseMessage = new Gson().toJson(pages.get(pagenumber));
I want to add another property to be read in javascript but that is unrelated to the list:
{"numberofpages":x}
I tried this:
JsonElement responsemessage = new Gson().toJsonTree(pages.get(pagenumber));
JsonObject message = (JsonObject) responsemessage;
message.addProperty("numberofpages",numberofpages);
... but I couldn't because responsemessage was a JSONArray. How can I encode more information in this String version of responseMessage to be read in javascript:
$.get("/lod1/Data",{pagenumber: page},function(list){
console.log(list);
//???
//if(list.numberofpages == 5){
// }
$.each(list,function(index,card){
$("#questionsforsets").append('<tr><td class="questioncell"><div class="longtexttd">'+card.card+'</div></td><td>'+card.category+'</td><td>'+card.made+'</td><td>'+card.missed+'</td></tr>');
});
},"json");
Well, as you found out, you cant add a property to a JSON Array.
If your responsemessage is an array, and you need to pass another value along with it, you should put this array and that value into a new object. Something like this should work:
JsonObject responseObject = new JsonObject();
responseObject.addProperty("pages", responsemessage);
responseObject.addProperty("numOfPages", numberOfPages);
(of course your JS code handling this response will need to be adjusted accordingly)

How to get attributes in Json String in servlet

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();
}
}

c# equivalent for serializing json

whats the equivalent for creating json serialized data for this javascript code:
chartData.push({date: "bla",value1: "bla1",value2: "bla2"});
chartData.push({date: "blx",value2: "blax2"});
The json will look something like this:
[{
"date": bla,
"value1": bla1,
"value2": bla3,
}, {
"date": blx,
"value2": blax2
}]
I tried creating a list of class, but when i dont assign the value1 property, the value will just be zero. But i dont want the property to be displayed in the json at all, when not assigned.
List <Models.HistoClass> HistoData= new List<Models.HistoClass>();
HistoData.Add(new Models.HistoClass {date="bla",value1="bla1",value2="bla3"});
HistoData.Add(new Models.HistoClass { date= "blx", value2="blax2" });
How should i create the datamodel to have a json like that?
Thanks!
If you're creating data manually in the way you show, you could use anonymous types to construct data the looks exactly how you want:
List <object> HistoData= new List<object>();
HistoData.Add(new {date="bla",value1="bla1",value2="bla3"});
HistoData.Add(new { date= "blx", value2="blax2" });
However, if you want to use a strong type and/or your code is initializing the values in the same way every time, but sometimes values just aren't present, then you can make the values nullable and tell JSON.NET to ignore null properties when serializing:
public class HistoClass
{
public string date;
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
public int? value1;
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
public int? value2;
}
...
List <Models.HistoClass> HistoData= new List<Models.HistoClass>();
HistoData.Add(new Models.HistoClass {date="bla",value1="bla1",value2="bla3"});
HistoData.Add(new Models.HistoClass { date= "blx", value2="blax2" });
You can use Json.NET's ShouldSerialize:
Public class DateAndValues
{
public DateTime Date {get; set;}
public Int32 Index {get; set;}
public Int32 Value1 {get; set;}
public Int16 Value2 {get; set;}
public bool ShouldSerializeValue1 ()
{
// your condition for serialization, for example even objects:
this.Index % 2 != 0;
}
}
This description:
To conditionally serialize a property, add a method that returns boolean with the same name as the property and then prefix the method name with ShouldSerialize. The result of the method determines whether the property is serialized. If the method returns true then the property will be serialized, if it returns false then the property will be skipped.
is taken from this link.
To actually serialize, of course, use:
var firstObj = new DateAndValues { Index = 1, .. };
var secondObj = new DateAndValues { Index = 2, .. };
string json =
JsonConvert.SerializeObject(new[] {firstObj, secondObj}, Formatting.Indented);
and according to the condition above, secondObj (even Index) will not have Value1.

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.

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