ASP.NET C# Multiple Value Json Serialize - json

I try to return user informations json value at my web page' load method. My code looks like this.
DataSet dsX = ReadSql("select top 14 * from fuyeler where inStatus = 1 and inUye = 1");
if (dsX.Tables.Count > 0)
{
OYUNCU oyuncular = new OYUNCU();
for (int i = 0; i < dsX.Tables[0].Rows.Count; i++)
{
oyuncular.oyuncuID = Convert.ToInt32(dsX.Tables[0].Rows[i]["inID"]);
oyuncular.oyuncuMail = dsX.Tables[0].Rows[i]["stMail"].ToString();
oyuncular.oyuncuPass = dsX.Tables[0].Rows[i]["stPass"].ToString();
oyuncular.oyuncuToken = dsX.Tables[0].Rows[i]["stToken"].ToString();
}
string json = JsonConvert.SerializeObject(oyuncular);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
}`
At the end it returns only 1 value of course. I have tried Arrays and lists but JsonConvert.SerializeObject(array or list) doesnt return as json value. It returns every values on 1 row. I want 1 row for 1 value. What should i do about it?
For this code below Json result looks like this,
{"oyuncuMail":"x#gmail.com","oyuncuPass":"x2008","oyuncuToken":"290620153513","oyuncuID":14}

This output is correct and should dispaly last record of the selected rows from your sql query because in your for loop you don't create new object, you assign values to the same object so it will take the values of the last row
you should do this if you want to get a list :
List<OYUNCU> listOyuncular = new List<OYUNCU>();
for (int i = 0; i < dsX.Tables[0].Rows.Count; i++)
{
var oyunclar = new OYUNCU();
oyuncular.oyuncuID = Convert.ToInt32(dsX.Tables[0].Rows[i]["inID"]);
oyuncular.oyuncuMail = dsX.Tables[0].Rows[i]["stMail"].ToString();
oyuncular.oyuncuPass = dsX.Tables[0].Rows[i]["stPass"].ToString();
oyuncular.oyuncuToken = dsX.Tables[0].Rows[i]["stToken"].ToString();
listOyuncular.Add(oyunclar);
}
string json = JsonConvert.SerializeObject(listOyuncular);

Related

Line: -1, Column: -1 System.StringException: Invalid id: '1294888839 ' Apex

I am trying to read csv from Document object and pass it to a method in apex. The csv only contains account Ids. I am getting an error as
"Line: -1, Column: -1
System.StringException: Invalid id: 'csvid173648'"
Below is my code:
String[] filecontent = new String[]{};
Document doc = [Select body from Document where id = 'mydocumentId35661'];
String stringbody = doc.body.tostring();
list<String> filelines = stringbody.split('\n');
System.debug('filelines'+filelines);
Set<Id> accountIdSet = new Set<Id>();
for(Integer i=1; i<filelines.size();i++)
{
String[] cols = new String[]{};
cols = filelines[i].split(',');
System.debug('check cols'+cols);
accountIdSet.add('\''+ cols[0] + '\'');
}
Map<String,Account_Achievement_Assignment__c> partnerAchievementMap;
partnerAchievementMap = PartnerAchievementHandler.createPartnerAchievementForExistingAccount(accountIdSet,false);
I can see the ids are passed correctly in the for loop. Tried to convert string to Id still get the same error. What is the mistake here?

I'm adding the data from the json file to my list, but the list is empty

I'm pulling the json file from an API and trying to add it to the list, but the list is empty afterwards.
Future<List<Posts>> getPosts() async {
var datas = await http.get(
Uri.parse("https://www.reddit.com/r/TechNewsToday/top.json?count=20"));
var jsonDatas = json.decode(datas.body);
List<Posts> postList = [];
for (int i = 0; i < 7; i++) {
var postJson = jsonDatas["data"]["children"][i];
String subreddit = postJson["data"]["subreddit"];
String title = postJson["data"]["title"];
String thumbnail = postJson["data"]["thumbnail"];
Posts post = Posts(title, thumbnail, subreddit);
postList.add(post);
}
print(postList.length);
return postList;
}
So when I tried this on my end I got a range error. Not sure where 7 comes from in your for loop but its probably safer to use the length of the children in the response. When I look at the json response, what you're trying to parse only has 5 items.
Maybe that changes, but all the more reason to not use a fixed number in your loop.
This works for me.
Future<List<Posts>> getPosts() async {
var datas = await http.get(
Uri.parse("https://www.reddit.com/r/TechNewsToday/top.json?count=20"));
var jsonDatas = json.decode(datas.body);
List<Posts> postList = [];
// this is the actual length of what you're trying to parse
final responseLength = jsonDatas["data"]["children"].length as int;
for (int i = 0; i < responseLength; i++) {
var postJson = jsonDatas["data"]["children"][i];
String subreddit = postJson["data"]["subreddit"];
String title = postJson["data"]["title"];
String thumbnail = postJson["data"]["thumbnail"];
Posts post = Posts(title, thumbnail, subreddit);
postList.add(post);
}
print(postList.length);
return postList;
}

How can I order my string in as3

A complex question :
I've got this code (not the complete code, but the essentials for the question, I think) :
var $pmm:String;
var $pms:String;
var $bmm:String;
var $bms:String;
function get haute1():String { return $pmm; };
function get haute2():String { return $pms; }
function get basse1():String { return $bmm; };
function get basse2():String { return $bms; };
accueil.todayHaute_txt.htmlText = haute1;
accueil.todayBasse_txt.htmlText = basse1;
accueil.todayHauteSecond_txt.htmlText = haute2;
accueil.todayBasseSecond_txt.htmlText = basse2;
"haute1" is an hour (in 24h format). Something like "13h25".
It changes everyday.
Question : How can put them in ascending order in AS3 ?
Example : If haute1 = 15h20, haute2= 6h00, basse1= 11h and basse2 = 17h, the function would put them in this order :
"haute2", then "basse1", then "haute1" and finally "basse2".
Thx
EDIT
I add this code that I have. is it helping you ?
/ Assigns hours and tidal heights
$pmm = convdateheure($tpbs[1 + $deltapm]);
$pms = convdateheure($tpbs[3 + $deltapm]);
$bmm = convdateheure($tpbs[2 - $deltapm]);
$bms = convdateheure($tpbs[4 - $deltapm]);
function convdateheure($valeur:Number):String
{
var $heure:Number = Math.floor($valeur);
var $minute:Number = Math.floor(Math.floor(($valeur - Math.floor($valeur)) * 100) * 0.6);
var hoursLabel:String = "", minsLabel:String = "";
if ($heure == 24) $heure = 0; // Check if at the 24 hour mark, change to 0
if ($heure < 10) hoursLabel += "0" + $heure.toString(); else hoursLabel = $heure.toString();
if ($minute < 10) minsLabel += "0" + $minute.toString(); else minsLabel = $minute.toString();
return hoursLabel + ":" + minsLabel;
}
If you want to order some dates written in some String format:
One way would be, depending on you date string format, just to push them into array and sort them as strings, then read them all.
Another way would be to first parse those strings into Date instances, and push their Date.time property to array, sort it, then do reverse: parse all time values from sorted array into new Date instances then use Date.toString or similar.
Assuming that $valuer is a numerical value:
var timesArray:Array = new Array();
var convertedTimesArray:Array = new Array();
function sortTimes():void{
timesArray.push($valuer);
timesArray.sort(Array.NUMERIC);
}
function convertTimes():void{
convertedTimesArray = []; // clear the array
for (var i:int = 0; i < timesArray.length; i++){
var s:String = convdateheure(timesArray[i]);
convertedTimesArray.push(s);
}
}
That should give you one array of actual times, sorted in numerical order, and one array sorted in the same numerical order, but converted to String values using your function.

Dealing with nested for loops in Swift for a JSON file

One of the JSON requests that I make returns a file with a bunch of nested information. The format is roughly as follows groups->individual group->teams in group.
Currently I am dealing with this with a nested for loop where I look at the outer groups and then run the inner loop to get the information for the individual teams.
I've uploaded a copy of the JSON file to paste bin, here is the link. http://pastebin.com/D14wYDEs. This particular example doesn't have that many groups and teams but its possible to have way more, which makes the concept of nested for loops seem impractical.
I was wondering if somebody had a suggestion as to a better system of doing this, or any suggestion really.
Heres my current code:
func generateTablaDePosiciones() {
estadisticaUtilizada = 3
var tablaDePosicionesJSON = getJSONStats(3,tkn,eqID)
//checks to see that contents != nil, meaning the JSON file was found
if tablaDePosicionesJSON != nil {
tablaDePosicionesArray.removeAll(keepCapacity: false)
var numeroDeGruposEnTablaDePosiciones = tablaDePosicionesJSON["grupos"].count
for var index = 0; index < numeroDeGruposEnTablaDePosiciones; ++index {
var grupo = tablaDePosicionesJSON["grupos"][index]["grupo"].string
var etiqueta1 = tablaDePosicionesJSON["grupos"][index]["etiqueta-1"].string
var etiqueta2 = tablaDePosicionesJSON["grupos"][index]["etiqueta-2"].string
var etiqueta3 = tablaDePosicionesJSON["grupos"][index]["etiqueta-3"].string
var etiqueta4 = tablaDePosicionesJSON["grupos"][index]["etiqueta-4"].string
var etiqueta5 = tablaDePosicionesJSON["grupos"][index]["etiqueta-5"].string
var preTablaDePosicionesNuevo = preTablaDePosiciones(grupo: grupo!, etiqueta1: etiqueta1!, etiqueta2: etiqueta2!, etiqueta3: etiqueta3!, etiqueta4: etiqueta4!, etiqueta5: etiqueta5!)
preTablaDePosicionesArray.append(preTablaDePosicionesNuevo)
numeroDeTablaDePosiciones = tablaDePosicionesJSON["grupos"][index]["lista-body"].count
for(var innerIndex = 0; innerIndex < numeroDeTablaDePosiciones; ++innerIndex) {
var rank = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["rank"].string
var equipoID = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["equipoID"].number! as Int
var nomEquipo = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["nom-equipo"].string
var d1 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d1"].string
var d2 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d2"].string
var d3 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d3"].string
var d4 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d4"].string
var d5 = tablaDePosicionesJSON["grupos"][index]["lista-body"][innerIndex]["d5"].string
var tablaDePosicionesNuevo = tablaDePosiciones(rank: rank!, equipoID: equipoID, nomEquipo: nomEquipo!, d1: d1!, d2: d2!, d3: d3!, d4: d4!, d5: d5!)
tablaDePosicionesArray.append(tablaDePosicionesNuevo)
}
}
} else {
estadisticaUtilizada = 0
println("Tabla de Posiciones JSON was nil")
}
}
I would use a while loop. Increment an index with each execution and then dynamically construct the key using that index. Collect your results in an array and then pass on that array instead of each individual object.
Also, you should really be unwrapping all these values as you're parsing them instead of force unwrapping (!). In this while loop you can use a conditional binding while let to handle that, and if it fails—i.e. it found no value for that key—it will exit.
Something like this:
var index = 1
var results = [String]()
while let etiqueta = grupo["etiqueta-\(index)"] as? String {
results.append( etiqueta )
index++
}
let preTablaDePosicionesNuevo = preTablaDePosiciones(grupo: name, etiquetas: results)
preTablaDePosicionesArray.append( preTablaDePosicionesNuevo )

Error msg on linq to dictionary-"an item of the same key value has already been added"

I'm trying do make a collection using linq based on ID which is a GUID.On using dictionary I'm getting error "An item with same key has already been added" Any suggestion?
foreach (Guid i in ar)
{
var prod = (from r in datacontext.item_tables's where r.itemID == i select r);
Dictionary<Guid, item_tables> tempdata =prod.ToDictionary(s => s.itemID);
Facet[] ftemp = new Facet[tempdata.Count];
string s1 = "";
ftemp[0] = new Facet("descriptiob", FacetType.Text, tempdata[i].Description);
ftemp[1] = new Facet("date", FacetType.Text, tempdata[i].uploaddate);
for (int iv = 0; iv < tempdata.Count; iv++)
{
s1 += tempdata[i].ProductName + " \n";
}
ftemp[2] = new Facet("ProductName", FacetType.Text, s1);
}
You're basically building your dictionary using this code:
datacontext
.item_tables
.Where(r => r.itemID == i)
.ToDictionary(s => s.itemID);
The Where is filtering the results to where itemID is a particular i (Guid) at a time, but can return zero, one, or more, results. Clearly the error you are getting says that for at least one value of i you are getting more than one record returned.
This means the issue either that your database isn't properly normalized or that you've got a logic error in your code.
It sounds like the latter to me.
Further down in your code you have this loop:
for (int iv = 0; iv < tempdata.Count; iv++)
{
s1 += tempdata[i].ProductName + " \n";
}
This says to me that you're expecting the tempdata dictionary to have more than one value - but you're building the dictionary using itemID as the key and this should only put one value in the dictionary based on your query. So something is wrong here in your logic.
Can you describe in more detail what you're trying to do?
Based on your comment below (without the clarification from my comment) this appears to be what you want:
var query =
from r in datacontext.item_tables
group r.ProductName by new
{
r.itemID,
r.Description,
r.uploaddate,
r.ItemName,
};
foreach (var items in query.ToArray())
{
var f0 = new Facet("descriptiob", FacetType.Text, items.Key.Description);
var f1 = new Facet("date", FacetType.Text, items.Key.uploaddate);
var f2 = new Facet("ProductName", FacetType.Text, String.Join("\n", items));
collection.AddItem(items.Key.ItemName, null, null, f0, f1, f2);
}