kotlin.kotlinnullpointerexception - json

JSON displays data get in Android and shows in TextView and TableLayout.JSON have Nine Records and its parsing using Retrofit2 and RXjava2.
All the data gets in android side and Store in ArrayList.
In ArrayList Size is Nine get All Data.
Textview shows data but in TableLayout only two record display another seven record is not display. in Third record goeson var tax_total its give Error : "kotlin.kotlinnullpointerexception"
What's the problem that the other data is not displayed?
private fun fetchYearData(){
val retrofit = APIClient.apIClient
if (retrofit != null) {
api = retrofit.create(APIInterface::class.java)
}
compositeDisposable!!.add(api.getSalesGSTData(1,1,"04/01/2018","31/03/2019")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe( {
displaySalesGSTData(it.salesGst) },
{
Toast.makeText(this,it.message,Toast.LENGTH_LONG).show() }))
}
private fun displaySalesGSTData(salesGSt : List<SalesGST>) {
salesGST = SalesGST()
tvSalesCompanyName.setText(salesGSt.get(1).Cmp_Name)
tvGSTIN.setText(salesGSt.get(1).GSTIN)
val rowHeader = TableRow(this#Sales)
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"))
rowHeader.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val headerText = arrayOf<String>("Sr.No.", "Invoice Type", "Bill No.", "Bill Date", "Firm Name", "GST NO","TAX Total","CGST","SGST","IGST","Net Amount")
for (c in headerText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_header)
tv.setTextColor(Color.parseColor("#3F51B5"))
tv.setTextSize(18F)
tv.setPadding(5, 5, 5, 5)
tv.setText(c)
rowHeader.addView(tv)
}
tableMarks.addView(rowHeader)
for (j in 0 until salesGSt.size)
{
var fName : String = salesGSt[j].FirmName!!
var invoice : String = salesGSt[j].InvoiceType!!
var bill_no : String = salesGSt[j].ChallanNo!!
var bill_date : String = salesGSt[j].ChallanDate!!
var gst_no : String = salesGSt[j].PartyGST!!
var tax_total : String = salesGSt[j].TaxTotal!!
var cgst : String = salesGSt[j].CGSTTotal!!
var igst : String = salesGSt[j].IGSTTotal!!
var sgst : String = salesGSt[j].SGSTTotal!!
var net_amount : String = salesGSt[j].ChallanAmount!!
var sr : Int = j
// dara rows
val row = TableRow(this#Sales)
row.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val colText = arrayOf<String>(sr.toString(),(invoice), bill_no, bill_date, fName, gst_no,tax_total,cgst,sgst,igst,net_amount)
for (text in colText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_shape)
tv.setTextSize(18F)
tv.setTextColor(Color.parseColor("#000000"))
tv.setPadding(5, 5, 5, 5)
tv.setText(text)
row.addView(tv)
}
tableMarks.addView(row)
}
JSON :
{"success":1,"salesGst":[{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"2778.75","TaxTotal":"2778.75","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":"CDE","SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"2203.0","TaxTotal":"2118.5","InvoiceType":"Tax Invoice","CGSTTotal":"52.96","PartyGST":"CDE","SGSTTotal":"52.96","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"VIKAS","ChallanNo":"2","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"6975.0","TaxTotal":"6975.0","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":null,"SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"2","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"420.0","TaxTotal":"403.75","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"20.19"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"3","ChallanDate":"2019-03-14 00:00:00","ChallanAmount":"4788.0","TaxTotal":"4560.0","InvoiceType":"Tax Invoice","CGSTTotal":"114.0","PartyGST":"CDE","SGSTTotal":"114.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"4","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"241.9","TaxTotal":"230.38","InvoiceType":"Tax Invoice","CGSTTotal":"5.76","PartyGST":"CDE","SGSTTotal":"5.76","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"5","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"5563.68","TaxTotal":"5101.5","InvoiceType":"Tax Invoice","CGSTTotal":"231.28","PartyGST":"CDE","SGSTTotal":"231.28","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"6","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"13238.0","TaxTotal":"12459.25","InvoiceType":"Tax Invoice","CGSTTotal":"389.29","PartyGST":"CDE","SGSTTotal":"389.29","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"7","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"2074.0","TaxTotal":"1975.0","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"98.75"}]}
xml :
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbarStyle="insideInset"
android:fadeScrollbars="true"
android:scrollbarSize="10dp"
android:fitsSystemWindows="true">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tableMarks"
android:stretchColumns="*"
android:layout_marginTop="20dp"
android:orientation="horizontal"
></TableLayout>
</HorizontalScrollView>
</ScrollView>

Related

json data parsing using retrofit and rxjava2 data display in Textview and TableLayout

JSON Data Parsing Using Retofit2 and Rxjava2. This Data get In ArrayList successfully. its ArrayList Size is Nine but its display only two Record in Table. After Two Record its Kotlin.NullPointerException.
JSON Data:
{"success":1,"salesGst":[{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"2778.75","TaxTotal":"2778.75","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":"CDE","SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"1","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"2203.0","TaxTotal":"2118.5","InvoiceType":"Tax Invoice","CGSTTotal":"52.96","PartyGST":"CDE","SGSTTotal":"52.96","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"VIKAS","ChallanNo":"2","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"6975.0","TaxTotal":"6975.0","InvoiceType":"Retail Invoice","CGSTTotal":"0.0","PartyGST":null,"SGSTTotal":"0.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"2","ChallanDate":"2019-03-13 00:00:00","ChallanAmount":"420.0","TaxTotal":"403.75","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"20.19"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"3","ChallanDate":"2019-03-14 00:00:00","ChallanAmount":"4788.0","TaxTotal":"4560.0","InvoiceType":"Tax Invoice","CGSTTotal":"114.0","PartyGST":"CDE","SGSTTotal":"114.0","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"4","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"241.9","TaxTotal":"230.38","InvoiceType":"Tax Invoice","CGSTTotal":"5.76","PartyGST":"CDE","SGSTTotal":"5.76","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"5","ChallanDate":"2019-03-15 00:00:00","ChallanAmount":"5563.68","TaxTotal":"5101.5","InvoiceType":"Tax Invoice","CGSTTotal":"231.28","PartyGST":"CDE","SGSTTotal":"231.28","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES GJ","ChallanNo":"6","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"13238.0","TaxTotal":"12459.25","InvoiceType":"Tax Invoice","CGSTTotal":"389.29","PartyGST":"CDE","SGSTTotal":"389.29","IGSTTotal":"0.0"},{"Cmp_Name":"ABC","GSTIN":"AAAA","FirmName":"SALES MH","ChallanNo":"7","ChallanDate":"2019-03-16 00:00:00","ChallanAmount":"2074.0","TaxTotal":"1975.0","InvoiceType":"Tax Invoice","CGSTTotal":"0.0","PartyGST":"ABC","SGSTTotal":"0.0","IGSTTotal":"98.75"}]}
Please Guide Me,After Getting How to Show in TableLayout.
In ArrayList Nine Record but in Table show only Two Record another seven record is not display. in third record taxtotal give kotlin.nullpointerException. what missing?
private fun displaySalesGSTData(salesGSt : List<SalesGST>) {
salesGST = SalesGST()
tvSalesCompanyName.setText(salesGSt.get(1).Cmp_Name)
tvGSTIN.setText(salesGSt.get(1).GSTIN)
val rowHeader = TableRow(this#Sales)
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"))
rowHeader.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val headerText = arrayOf<String>("Sr.No.", "Invoice Type", "Bill No.", "Bill Date", "Firm Name", "GST NO","TAX Total","CGST","SGST","IGST","Net Amount")
for (c in headerText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_header)
tv.setTextColor(Color.parseColor("#3F51B5"))
tv.setTextSize(18F)
tv.setPadding(5, 5, 5, 5)
tv.setText(c)
rowHeader.addView(tv)
}
tableMarks.addView(rowHeader)
for (j in 0 until salesGSt.size)
{
/*val jsonObject1 = jsonArray.getJSONObject(j)
val date = jsonObject1.getString("ExamDate")
val inputFormatter1 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val date1 = inputFormatter1.parse(date)
val outputFormatter1 = SimpleDateFormat("dd-MMM-yyyy")
ExamDate = outputFormatter1.format(date1)*/
/* String replaceDate = date.replace("/Date(", "").replace(")/", "");
Long getDate = Long.valueOf(replaceDate);
ExamDate = dateFormat.format(getDate);*/
/*Subject = jsonObject1.getString("subject")
ExamName = jsonObject1.getString("ExamName")
TotalMark = jsonObject1.getLong("TotalMarks")
PassingMark = jsonObject1.getLong("PassingMarks")
Mark = jsonObject1.getLong("Marks")*/
var fName : String = salesGSt.get(j).FirmName!!
var invoice : String = salesGSt.get(j).InvoiceType!!
var bill_no : String = salesGSt.get(j).ChallanNo!!
var bill_date : String = salesGSt.get(j).ChallanDate!!
var gst_no : String = salesGSt.get(j).PartyGST!!
var tax_total : Double = salesGSt.get(j).TaxTotal!!.toDouble()
var cgst : String = salesGSt.get(j).CGSTTotal!!
var igst : String = salesGSt.get(j).IGSTTotal!!
var sgst : String = salesGSt.get(j).SGSTTotal!!
var net_amount : String = salesGSt.get(j).ChallanAmount!!
var sr : Int = j + 1
// dara rows
val row = TableRow(this#Sales)
row.setLayoutParams(TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT))
val colText = arrayOf<String>(sr.toString(),(invoice), bill_no, bill_date, fName, gst_no, tax_total.toString(),cgst,sgst,igst,net_amount)
for (text in colText)
{
val tv = TextView(this#Sales)
tv.setLayoutParams(TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT))
tv.setGravity(Gravity.CENTER)
// tv.setBackgroundResource(R.drawable.table_shape)
tv.setTextSize(18F)
tv.setTextColor(Color.parseColor("#3F51B5"))
tv.setPadding(5, 5, 5, 5)
tv.setText(text)
row.addView(tv)
}
tableMarks.addView(row)
}
}
The 3rd item, salesGst[2], is "PartyGST": null. Your json deserializer library won't handle non-null fields as it's written in Java. I assume you have a data class where PartGST is defined as non-null, yet the deserializer will still parse it as null. Therefore, when you access PartyGST then you will receive a NullPointerException because Kotlin is expecting it to be non-null. This is a good article, which explains in more detail:
I've trusted you! You promised no null pointer exceptions!
A solution to this would be to have two models. The DTO (for JSON response) where all fields are optional and your internal model (used by your app), where you define which fields you want to be optional. Then you can have a mapper to handle the case where a field is null in the DTO, but non-null in your internal model:
// Models for your API response
data class SalesGstsDTO(val gsts: List<GstDTO>)
data class GstDTO(val name: String?, val surname: String?)
// Internal models used by your app
data class SalesGsts(val gsts: List<Gst>)
data class Gst(val name: String, val surname: String?)
class SalesGstDTOMapper {
fun mapToSalesGsts(salesGstsDTO: SalesGstsDTO): SalesGsts {
val gsts = mutableListOf<Gst>()
salesGstsDTO.gsts.map {
val name = it.name ?: return#map // Skips this item. You could handle this how you wish
val surname = it.surname
val gst = Gst(name, surname)
gsts.add(gst)
}
return SalesGsts(gsts)
}
}
This also allows you to decouple your app from the JSON response.

JsonResult is sending Json parsed object as empty array collection to browser [[]],[[]]

I'm trying to add to the JsonResult object a parsed Json string, but I couldn't do it, the parser object in the browser is shown as:
"filter":[[[]],[[[],[]]]]
This is the full code
public JsonResult AjaxStandardGet(int id)
{
Standard ec = db.Standard.FirstOrDefault(s => s.IdStandard == id);
// inside filter: { "KeyDynamic1": "Value1", "KeyDynamic2": [ "AAA", "DDD"] }
var filter = JsonConvert.DeserializeObject(ec.Filter);
return Json(new
{
ec.IdStandard,
ec.Description,
filter,
ec.Observations,
Services = ec.StandardServices.Select(s => new {
s.IdStandardServices,
Tecnology = s.Tecnology?.Nombre,
ServiceType = s.ServiceType?.Description,
s.Quantity,
s.Cost,
Options = (!string.IsNullOrEmpty(s.Options) ? s.Options.Split(',') : null),
Total = s.Quantity * s.Cost
}),
Success = true
});
}
I can't create the model object because the filters are not allways the same.
I tried this:
Dictionary<string, object> filter = JsonConvert.DeserializeObject<Dictionary<string, object>>(ec.Filter);
And I get
"filter":{"KeyDynamic1":"Value1","KeyDynamic2":[[],[]]}
I suggest you to JToken or dynamic:
JToken filter = JToken.Parse(ec.Filter);
dynamic filter = JsonConvert.DeserializeObject<dynamic>(ec.Filter);
Here is working fiddle.
Update
It seems that JavaScriptSerializer is not able to do it. So you can serialize your result using Newtonsoft.Json and return it as a string:
var result = new
{
ec.IdStandard,
ec.Description,
filter,
ec.Observations,
Services = ec.StandardServices.Select(s => new {
s.IdStandardServices,
Tecnology = s.Tecnology?.Nombre,
ServiceType = s.ServiceType?.Description,
s.Quantity,
s.Cost,
Options = (!string.IsNullOrEmpty(s.Options) ? s.Options.Split(',') : null),
Total = s.Quantity * s.Cost
}),
Success = true
};
var json = JsonConvert.SerializeObject(result);
return Content(json, "application/json");

remove duplicate entries while executing repeated job to save json data in mongo

I am having following structure currently present in my database, i am executing a service to fetch data from REST api and storing it to my database , so that i can use it to display it frequently on UI as like caching a data
db.countDetails.find().pretty()
{
"_id" : ObjectId("5670xxxx"),
"totalProjectCount" : 53,
"activeProjectCount" : 29,
"completedProjectCount" : 1,
"userCount" : 85
}
{
"_id" : ObjectId("5670ea97f14c717a903e8423"),
"totalProjectCount" : 48,
"activeProjectCount" : 41,
"completedProjectCount" : 0,
"userCount" : 123
}
My collection is going to remain same only values will be going to change, so please suggest me a way in which i can place the updated values in mongo and at the same time i can fetch data on my UI
my new values might be like
db.countDetails.find().pretty()
{
"_id" : ObjectId("5670xxxx"),
"totalProjectCount" : 23,
"activeProjectCount" : 17,
"completedProjectCount" : 1,
"userCount" : 60
}
{
"_id" : ObjectId("5670ea97f14c717a903e8423"),
"totalProjectCount" : 45,
"activeProjectCount" : 40,
"completedProjectCount" : 0,
"userCount" : 113
}
function to fetch data from REST api
def getCount(String companyName, String apiKey) {
//declaration section
List returnList = []
int totalProjectCount = 0 //variable to hold total no of projects value
int activeProjectCount = 0 //variable to hold total active projects value
int completedProjectCount = 0 //variable to hold total completed projects value
int userCount = 0 //variable to hold total active user count
String userAPIKey = apiKey //user API key for authorization
String method = 'GET' //method of request
String totalProjectURL = "https://"+ companyName + ".teamwork.com/projects.json?status=ALL" // Url to access All projects
StringBuilder out = getConnection(totalProjectURL, method, userAPIKey) //String builder to hold result
//catching result into json
JSONObject object = new JSONObject(out.toString()) //JSON object to store String in json format
totalProjectCount = object.projects.length()
String activeProjectCountURL = "https://"+ companyName + ".teamwork.com/projects.json?status=ACTIVE" // Url to access Active projects
out = getConnection(activeProjectCountURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
activeProjectCount = object.projects.length()
String completedProjectCountURL = "https://"+ companyName + ".teamwork.com/projects.json?status=COMPLETED" // Url to access completed projects
out = getConnection(completedProjectCountURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
completedProjectCount = object.projects.length()
String peopleURL = "https://"+ companyName + ".teamwork.com/people.json" // Url to access total active users
out = getConnection(peopleURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
userCount = object.people.length()
Map returnMap = [:]
returnMap.put('totalProjectCount', totalProjectCount)
returnMap.put('activeProjectCount', activeProjectCount)
returnMap.put('completedProjectCount', completedProjectCount)
returnMap.put('userCount', userCount)
addCount(returnMap, 'curo', 'countDetails')
println('project count successfully saved.')
}
function to add countDetails to mongo
def addCount(Map userMap, String dbName, String collectionName) {
try {
DB db = mongo.getDB(dbName)
DBCollection table = db.getCollection(collectionName)
table.insert(userMap as BasicDBObject)
def srvcResponseObj = [ responseStatus : "pass", responseCode : 200 ]
return srvcResponseObj
}
catch (Exception e)
{
println "Exception related to Mongo add record"
e.printStackTrace()
def srvcResponseObj = [ responseStatus : "fail", responseCode: 400 ]
return srvcResponseObj
}
}
function to fetch data from mongo
def fetchCountDetails(String databaseName, String collectionName) {
println 'inside fetch count details'
try {
DB db = mongo.getDB(databaseName)
DBCollection table = db.getCollection(collectionName)
DBCursor cursor = table.find()
Map returnCountMap = [:]
List temp = []
int cursorCounter = 0
while(cursor.hasNext()) {
Map temporaryMap = [:]
BasicDBObject doc = (BasicDBObject) cursor.next()
doc.remove('_id')
temp.add(doc)
cursorCounter++
}
returnCountMap.put('totalProjectCount', temp.totalProjectCount.sum())
returnCountMap.put('activeProjectCount',temp.activeProjectCount.sum())
returnCountMap.put('completedProjectCount',temp.completedProjectCount.sum())
returnCountMap.put('userCount',temp.userCount.sum())
if(cursorCounter>1)
println "Multiple objects found for eventID"
if(cursorCounter==0)
println "No objects found for eventID"
return returnCountMap
}
catch (Exception e)
{
println "Exception related to Mongo >> fetchUserDetails"
e.printStackTrace()
def srvcResponseObj = [ responseStatus : "fail", responseCode: 400 ]
return srvcResponseObj
}
}
now i am making request to REST api after fixed amount of interval and my response gets changed in terms of values, but if i call the add function again and again my documents get duplicated in mongodb and my expected result is that my new values gets reflected in mongodb

JSON is not working

I have one dropdown in the table.Once I make Onchange event I got all the table value and I want to convert it into json to send it to the servlet.
var item = [];
function dropDownOnChange(e) {
var selectedValue = e.options[e.selectedIndex].value;
alert("selectedValue:" + selectedValue);
var currentRow= $(e).closest("tr");
var AccountNo = $("td:eq(0)",$(currentRow)).text();
alert("accountno"+AccountNo);
var AccountType =$("td:eq(1)",$(currentRow)).text();
alert("acctyp"+AccountType);
var AcctypID = $("td:eq(3)",$(currentRow)).text();
alert("accID"+AcctypID);
Here I tried to convert it to JSON. I want to send this JSON value on my final save.
var objddlvalue = {};
objddlvalue["AccountNo"] = AccountNo;
objddlvalue["AccountType"] = AccountType;
objddlvalue["Account Type_Val"] = AcctypID;
objddlvalue["AccountStatus"] = selectedValue;
item.push(objddlvalue);
console.log(item);
jsonObj1 = JSON.stringify(item);
console.log(jsonObj1);
I am getting my JSON value like:
[{
"AccountNo": "89348734",
"AccountType": "Credit",
"Account Type_Val": "21",
"AccountStatus": "Invalid"
}]
When I check on online JSON checker it says the format is correct. But when I access it form servlet I can not parse it to jarray.
JSONObject jsonObj1 = (JSONObject)JSONValue.parse(request.getParameter("jsondata1"));
System.out.println("Json Object........"+jsonObj1.toJSONString());
JSONArray arr = (JSONArray) jsonObj.get(jsonObj1);
How to loop through my JSON object?
public static void main(String[] args) {
String jsonExternal = "[" +
"{"+
"\"AccountNo\": \"89348734\","+
"\"AccountType\": \"Credit\","+
"\"Account Type_Val\": \"21\","+
"\"AccountStatus\": \"Invalid\""+
"},"+
"{"+
"\"AccountNo\": \"89348734_test\","+
"\"AccountType\": \"Credit_test\","+
"\"Account Type_Val\": \"21_test\","+
"\"AccountStatus\": \"Invalid_test\""+
"}]";
JSONArray arr = (JSONArray)JSONValue.parse(jsonExternal);
for(Object obj : arr) {
JSONObject jsonObj = (JSONObject)obj;
Collection keySet = jsonObj.keySet();
Collection entrySet = jsonObj.entrySet();
Collection values = jsonObj.values();
for(Object o : keySet) {
System.out.println(o.toString());
}
for(Object o : entrySet) {
System.out.println(o.toString());
}
for(Object o : values) {
System.out.println(o.toString());
}
System.out.println(jsonObj.get("AccountNo"));
System.out.println(jsonObj.get("AccountType"));
System.out.println(jsonObj.get("Account Type_Val"));
System.out.println(jsonObj.get("AccountStatus"));
}
}

Is there a good string pluralization library for actionscript?

I haven't found a good library actionscript library for this yet.
I want to do things like:
Inflection.pluralize( "cat" ) == "cats"
Inflection.pluralize( "fish" ) == "fish"
I know ruby on rails has a library like this build in; and javascript has a really nice one as well: http://code.google.com/p/inflection-js/.
Any one know of a similar thing for actionscript?
Google says:
http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/
package
{
public class Inflect
{
private static var plural : Array = [
[/(quiz)$/i, "$1zes"],
[/^(ox)$/i, "$1en"],
[/([m|l])ouse$/i, "$1ice"],
[/(matr|vert|ind)ix|ex$/i, "$1ices"],
[/(x|ch|ss|sh)$/i, "$1es"],
[/([^aeiouy]|qu)y$/i, "$1ies"],
[/(hive)$/i, "$1s"],
[/(?:([^f])fe|([lr])f)$/i, "$1$2ves"],
[/(shea|lea|loa|thie)f$/i, "$1ves"],
[/sis$/i, "ses"],
[/([ti])um$/i, "$1a"],
[/(tomat|potat|ech|her|vet)o$/i, "$1oes"],
[/(bu)s$/i, "$1ses"],
[/(alias|status)$/i, "$1es"],
[/(octop)us$/i, "$1i"],
[/(ax|test)is$/i, "$1es"],
[/(us)$/i, "$1es"],
[/s$/i, "s"],
[/$/i, "s"]
];
private static var singular : Array = [
[/(quiz)zes$/i, "$1"],
[/(matr)ices$/i, "$1ix"],
[/(vert|ind)ices$/i, "$1ex"],
[/^(ox)en$/i, "$1"],
[/(alias|status)es$/i, "$1"],
[/(octop|vir)i$/i, "$1us"],
[/(cris|ax|test)es$/i, "$1is"],
[/(shoe)s$/i, "$1"],
[/(o)es$/i, "$1"],
[/(bus)es$/i, "$1"],
[/([m|l])ice$/i, "$1ouse"],
[/(x|ch|ss|sh)es$/i, "$1"],
[/(m)ovies$/i, "$1ovie"],
[/(s)eries$/i, "$1eries"],
[/([^aeiouy]|qu)ies$/i, "$1y"],
[/([lr])ves$/i, "$1f"],
[/(tive)s$/i, "$1"],
[/(hive)s$/i, "$1"],
[/(li|wi|kni)ves$/i, "$1fe"],
[/(shea|loa|lea|thie)ves$/i,"$1f"],
[/(^analy)ses$/i, "$1sis"],
[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, "$1$2sis"],
[/([ti])a$/i, "$1um"],
[/(n)ews$/i, "$1ews"],
[/(h|bl)ouses$/i, "$1ouse"],
[/(corpse)s$/i, "$1"],
[/(us)es$/i, "$1"],
[/s$/i, ""]
];
private static var irregular : Array = [
['move' , 'moves'],
['foot' , 'feet'],
['goose' , 'geese'],
['sex' , 'sexes'],
['child' , 'children'],
['man' , 'men'],
['tooth' , 'teeth'],
['person' , 'people']
];
private static var uncountable : Array = [
'sheep',
'fish',
'deer',
'series',
'species',
'money',
'rice',
'information',
'equipment'
];
public static function pluralize( string : String ) : String
{
var pattern : RegExp;
var result : String;
// save some time in the case that singular and plural are the same
if (uncountable.indexOf(string.toLowerCase()) != -1)
return string;
// check for irregular singular forms
var item : Array;
for each ( item in irregular )
{
pattern = new RegExp(item[0] + "$", "i");
result = item[1];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
// check for matches using regular expressions
for each ( item in plural)
{
pattern = item[0];
result = item[1];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
return string;
}
public static function singularize( string : String ) : String
{
var pattern : RegExp;
var result : String
// save some time in the case that singular and plural are the same
if (uncountable.indexOf(string.toLowerCase()) != -1)
return string;
// check for irregular singular forms
var item : Array;
for each ( item in irregular )
{
pattern = new RegExp(item[1] + "$", "i");
result = item[0];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
// check for matches using regular expressions
for each ( item in singular)
{
pattern = item[0];
result = item[1];
if (pattern.test(string))
{
return string.replace(pattern, result);
}
}
return string;
}
public static function pluralizeIf(count : int, string : String) : String
{
if (count == 1)
return "1 " + string;
else
return count.toString() + " " + pluralize(string);
}
}
}