String Equation parser issue - android

I'm coding a method that solve various kind of equation. Now I want that the method receives a String equation that could be in the forms:
ax^2+bx+c=0
or
*ax^2+c=0*
or
bx+c=0
etc. and the order shouldn't matter.
My problem is: How could I parse the equation according the "x" grade?
The eq could contains more values of the same grade for example 2x^2+4x^2+3x+8=2 (max grade x^3).
My method should assign the a value to double a[] if on the left or on the right of a there is x^2, double b[], if on the left or on the right there is x, and double c[] if there isn't any x variable near the value (and should change the value sign if the therms is after the =).
Convert a String number in a double is simple but I don't know how I could disassemble the input String according the x grade as described.

Tested for -2x + 3x^2 - 2 + 3x = 3 - 2x^2
public Double[] parseEquation(String equation)
{
Log.d(TAG, "equation: " + equation);
// Remove all white spaces
equation = equation.replaceAll("[ ]", "");
// Get the left and right sides of =
String[] sides = equation.split("[=]"); // should be of size 2
boolean leftNegative = false;
boolean rightNegative = false;
if (sides.length != 2)
{
// There is no = or more than one = signs.
}
else
{
// if sides i starts with + remove the +
// if - we remove and put it back later
for (int i = 0; i < 2; i++)
{
if (sides[i].charAt(0) == '+')
{
sides[i] = sides[i].substring(1);
}
}
if (sides[0].charAt(0) == '-')
{
leftNegative = true;
sides[0] = sides[0].substring(1);
}
if (sides[1].charAt(0) == '-')
{
rightNegative = true;
sides[1] = sides[1].substring(1);
}
}
Log.d(TAG, "left side:" + sides[0] + " right side: " + sides[1]);
// Terms without signs need to find out later
String[] leftTerms = sides[0].split("[+-]");
String[] rightTerms = sides[1].split("[+-]");
int length = leftTerms[0].length();
if (leftNegative)
{
leftTerms[0] = "-" + leftTerms[0];
}
// put in the minus sign for the rest of the terms
for (int i = 1; i < leftTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[0].charAt(length));
if (sides[0].charAt(length) == '-')
{
leftTerms[i] = "-" + leftTerms[i];
length += leftTerms[i].length();
}
else
{
length += leftTerms[i].length() + 1;
}
}
length = rightTerms[0].length();
if (rightNegative)
{
rightTerms[0] = "-" + rightTerms[0];
}
for (int i = 1; i < rightTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[1].charAt(length));
if (sides[1].charAt(length) == '-')
{
rightTerms[i] = "-" + rightTerms[i];
length += rightTerms[i].length();
}
else
{
length += rightTerms[i].length() + 1;
}
}
// Now we put all the factors and powers in a list
List<ContentValues> leftLists = new ArrayList<ContentValues>();
// left side
for (int i = 0; i < leftTerms.length; i++)
{
Log.d(TAG, "leftTerm: " + leftTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = leftTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no x mean a constant term
contentValues.put("factor", leftTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = leftTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = leftTerms[i].substring(indexOfX + 2).trim();
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
leftLists.add(contentValues);
}
List<ContentValues> rightLists = new ArrayList<ContentValues>();
for (int i = 0; i < rightTerms.length; i++)
{
Log.d(TAG, "rightTerm: " + rightTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = rightTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no hat mean a constant term
contentValues.put("factor", rightTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = rightTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = rightTerms[i].substring(indexOfX + 2).trim();
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
rightLists.add(contentValues);
}
// Now add the factors with same powers.
// Suppose we solve for cubic here the end result will be
// 4 terms constant, x, x^2 and x^3
// Declare a double array of dim 4 the first will hold constant
// the second the x factor etc...
// You can allow arbitrary power by looping through the lists and get the max power
Double[] result = new Double[]{0.0, 0.0, 0.0, 0.0};
for (ContentValues c : leftLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] += c.getAsDouble("factor");
break;
case 1:
result[1] += c.getAsDouble("factor");
break;
case 2:
result[2] += c.getAsDouble("factor");
break;
case 3:
result[3] += c.getAsDouble("factor");
break;
}
}
for (ContentValues c : rightLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] -= c.getAsDouble("factor");
break;
case 1:
result[1] -= c.getAsDouble("factor");
break;
case 2:
result[2] -= c.getAsDouble("factor");
break;
case 3:
result[3] -= c.getAsDouble("factor");
break;
}
}
Log.d(TAG, "constant term = " + result[0] + ", x^1 = " + result[1]
+ ", x^2 = " + result[2] + ", x^3 = " + result[3]);
return result;
}

If you weren't limited by Android, I'd suggest using a lexer and parser. These are code generators, so they can work anywhere the base language works, but they tend to produce bloated code. Android might not appreciate that.

Related

How to set text of multiple codes in one text view

Please have a look at this code and at the bottom is the question. Thanks for your help
int i,fact=1;
String value = edtLCM.getText().toString();
for (i = Integer.parseInt(value); i >= 1; i--) {
fact = fact * i;
if (i > 1) {
String one = i + " x ";
System.out.print(i + " x ");
} else {
System.out.print(i);
String two = String.valueOf(i);
}
}
System.out.println(" = " + fact);
LCMResult.setText("");
I want to set the textview of all the 3 "System.out.println()" in one line. The desired result would be like this(if a user input 4 in the edtLCM): 4x3x2x1 = 24
Use a StringBuilder to put the new strings together instead of using system out.
int i,fact=1;
String value = edtLCM.getText().toString();
StringBuilder sb = new StringBuilder(); // find a better name
for (i = Integer.parseInt(value); i >= 1; i--) {
fact = fact * i;
if (i > 1) {
String one = i + " x ";
// System.out.print(i + " x ");
sb.append(i).append(" x ");
} else {
//System.out.print(i);
sb.append(i);
String two = String.valueOf(i);
}
}
//System.out.println(" = " + fact);
sb.append(" = ").append(fact);
String result = sb.toString(); // will be 4 x 3 x 2 x 1 = 24
LCMResult.setText("");

MPAndroidChart stacked bar chart shows wrong/duplicated values

I'm trying to build a bar chart to show daily data of the week using MPAndroidChart. the data is shown localized so they're arranged depending on the first day of the week (Monday or Sunday). Some data get duplicated and added to several bars and some are show in wrong bars. I've been trying to solve this for a week and had no luck.
This is how I process data:
List<String> dailyIncomes = new ArrayList<>(7);
List<String> dailyExpenses = new ArrayList<>(7);
for (int x = 0; x < 7; x++) {
dailyIncomes.add("0");
dailyExpenses.add("0");
}
for (int i = 0; i < transactionsList.size(); i++) {
TransactionItem currentTransaction = transactionsList.get(i);
DateTimeHandler dateTimeHandler = new DateTimeHandler(currentTransaction.getUserDate()); //my own class to get day, week or year
int transactionYear = dateTimeHandler.getYear();
int transactionWeek = dateTimeHandler.getWeekOfYear();
int transactionDay = dateTimeHandler.getDayOfWeek();
if (transactionWeek == week && transactionYear == year) {
for (int d = 0; d < 7; d++) {
if (d + 1 == transactionDay) {
if (weekFields.getFirstDayOfWeek().getValue() == 7) {
if (transactionDay == 7) {
if (currentTransaction.getPrefix().equals("+")) {
double dailyTotal = Double.parseDouble(dailyIncomes.get(0)) + currentTransaction.getAmountValue();
dailyIncomes.add(0, "" + dailyTotal);
} else {
double dailyTotal = Double.parseDouble(dailyExpenses.get(0)) + currentTransaction.getAmountValue();
dailyExpenses.add(0, "" + dailyTotal);
}
} else {
if (currentTransaction.getPrefix().equals("+")) {
double dailyTotal = Double.parseDouble(dailyIncomes.get(d + 1)) + currentTransaction.getAmountValue();
dailyIncomes.add(d + 1, "" + dailyTotal);
} else {
double dailyTotal = Double.parseDouble(dailyExpenses.get(d + 1)) + currentTransaction.getAmountValue();
dailyExpenses.add(d + 1, "" + dailyTotal);
}
}
} else {
if (currentTransaction.getPrefix().equals("+")) {
double dailyTotal = Double.parseDouble(dailyIncomes.get(d)) + currentTransaction.getAmountValue();
dailyIncomes.add(d, "" + dailyTotal);
} else {
double dailyTotal = Double.parseDouble(dailyExpenses.get(d)) + currentTransaction.getAmountValue();
dailyExpenses.add(d, "" + dailyTotal);
}
}
}
}
}
}
WeeklyReport weeklyReport = new WeeklyReport(.....,dailyIncomes, dailyExpenses,....);
//to load next cards
weekCount++;
if (this.week == 1) {
yearCount++;
this.year = this.year - yearCount;
}
this.week = LocalDate.now()
.minusYears(yearCount)
.minusWeeks(weekCount)
.get(weekFields.weekOfWeekBasedYear());
weeklyReportList.add(weeklyReport);
adapter.submitList(weeklyReportList);
adapter.notifyItemInserted(adapter.getItemCount() + 1);
How I set data to the chart:
List<BarEntry> dailyDetails = new ArrayList<>();
for (int i = 0; i < 7; i++)
dailyDetails.add(new BarEntry(
(float) i, new float[]{
Float.parseFloat(weeklyReport.getDailyIncomes().get(i)),
Float.parseFloat(weeklyReport.getDailyExpenses().get(i))
}));
BarDataSet dailyDetailsSet = new BarDataSet(dailyDetails, "");
String[] labels = {context.getString(R.string.incomes), context.getString(R.string.expenses)};
//add x axis labels (days of week)
WeekFields weekFields = WeekFields.of(Locale.getDefault());
int firstDay = weekFields.getFirstDayOfWeek().getValue();
Log.i(TAG, "first day: " + firstDay);
final List<String> xLabels = new ArrayList<>();
for (int x = 0; x < 7; x++)
xLabels.add("DAY");
if (firstDay == 7) {
xLabels.add(0, LocalDate.now().with(DayOfWeek.of(7)).getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault()));
for (int z = 1; z < 7; z++)
xLabels.add(z, LocalDate.now().with(DayOfWeek.of(z)).getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault()));
} else
for (int y = 0; y < 7; y++)
xLabels.add(LocalDate.now().with(DayOfWeek.of(y + 1)).getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.getDefault()));
dailyDetailsSet.setStackLabels(labels);
BarData data = new BarData(dailyDetailsSet);
chartView.setData(data);
chartView.getXAxis().setValueFormatter(new IndexAxisValueFormatter() {
#Override
public String getFormattedValue(float value) {
return xLabels.get((int) value);
}
});
chartView.invalidate();
The chart looks like this:
I already tried using switch statements instead of loops but no luck. I'm sure that the data is accurate because there are some other charts like budget and monthly reports and nothing's wrong with them. It must be some silly mistake and I've been trying to fix this for three days but there's always something wrong.
Could someone help me and point out what I'm doing wrong? I'd appreciate it so much. Thanks. (Sorry if there's bad English)
Please ask me if you need to see more of the code.

A simple calculator

I'm new to Android. I'm trying to develop my first calculator. My calculator output is good, but I'm trying to make some changes to it. Please suggest. My output is 2+2=4.0 How can I get 4 if I put 2+2 and 4.0 when I put 2.8+1.2.
Also, please help me out in trying to figure out how can i keep on adding till i press =.
My code that I'm looking at is below:
private View.OnClickListener buttonClickListerner = new
View.OnClickListener() {
float r;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.clear:
screen.setText("");
operator.setText("");
FirstNum= 0;
showtext.setText("");
break;
case R.id.buttonAdd:
mMath("+");
operator.setText("+");
showtext.setText(String.valueOf(FirstNum));
break;
case R.id.buttonMinus:
mMath("-");
operator.setText("-");
break;
case R.id.buttonMul:
mMath("*");
operator.setText("*");
break;
case R.id.buttonequal:
mResult();
break;
case R.id.buttonDiv:
mMath("/");
operator.setText("/");
break;
case R.id.buttonPercent:
mMath("%");
r = FirstNum / 100;
showtext.setText("[" + String.valueOf(FirstNum) + "%" + "]");
screen.setText(String.valueOf(r));
break;
default:
String num = ((Button) v).getText().toString();
getKeyboard(num);
break;
}
}
};
public void mMath(String str){
FirstNum = Float.parseFloat(screen.getText().toString());
operation = str;
screen.setText("");
}
public void getKeyboard(String str){
String CurrentScreen = screen.getText().toString();
if(CurrentScreen.equals("0"))
CurrentScreen = "";
CurrentScreen = CurrentScreen + str;
screen.setText(CurrentScreen);
String ExScreen = CurrentScreen;
screen.setText(ExScreen);
}
public void mResult(){
float SecondNum = Float.parseFloat(screen.getText().toString());
float ThirdNum = Float.parseFloat(screen.getText().toString());
float result = 0;
//float exresult = result;
if(operation.equals("+")){
result = FirstNum + SecondNum;
// exresult = result + ThirdNum;
}
if(operation.equals("-")){
result = FirstNum - SecondNum;
//exresult = result - ThirdNum;
}
if(operation.equals("*")){
result = FirstNum * SecondNum;
//exresult = result * ThirdNum;
}
if(operation.equals("/")){
result = FirstNum / SecondNum;
//exresult = result / ThirdNum;
}
screen.setText(String.valueOf(result));
//screen.setText(String.valueOf(exresult));
showtext.setText(String.valueOf(FirstNum + operation + SecondNum));
//showtext.setText(String.valueOf(FirstNum + operation + SecondNum +
operation + ThirdNum));
}
}
I guess you should do your calculations as double and then before setting the output to TextView (or whatever you are using), check for the output if int or not and then decide which form of output to set to the TextView.
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integral type
}
See this
Edit:
The idea is to check that fractional part of the number is 0 (i.e.) the number is integer.
You may also Use these conditions [if true then variable is an Integer]
// check if
variable == Math.ceil(variable)
or
// check if
variable == Math.round(variable)
Also Math.round(float f) will return the interger form of the number!
To add multiple item first set up an array with a size of how long the user can input and then loop through each array adding them equivalently... i know this is a vague answer but you can ask me if anything is unclear and also an up vote would be nice. you got the right idea for the cases just try the following code
// array to sum
int[] numbers = new int[]{ 10, 10, 10, 10};
int sum = 0;
for (int i=0; i < numbers.length ; i++) {
sum = sum + numbers[i];
}
System.out.println("Sum value of array elements is : " + sum);
}

Android ArrayList of int

I'm new with android and java, so I apologize if what I say is not entirely correct.
In my application I'd like to convert an ArrayList to integer
to increase each value with a +1. Please note the commented out part to understand where is my problem. I can't find the right way..
This is what I do for now:
public String mRequest(String mUrl, String mAuth, String mParam, String customerId, ArrayList filter) {
InputStream mStreamResponse;
String mString = null;
try {
URL obj = new URL(mUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", mAuth);
con.setRequestProperty("X-Limit", String.valueOf(xLimit));
con.setRequestProperty("X-Skip", String.valueOf(xSkip));
con.setRequestProperty("X-Sort", "{\"created\":-1}");
String parameters = null;
System.out.println("Value of mParam -> " + mParam);
if (mParam != null && customerId != null) {
Log.e("ERROR", "Ricerca per parametro e customerId");
} else if (mParam != null) {
parameters = "\"number\":{\"$regex\":" + mParam + "}";
} else if (customerId != null) {
parameters = "\"customer.id\":{\"$eq\":" + "\"" + customerId + "\"" + "}";
} else {
parameters = "\"number\":{\"$regex\":\"\"}";
}
System.out.println("parameters");
System.out.println(parameters);
if (filter != null) {
//convert ArrayList to Array
Object[] mArray = filter.toArray();
String filterGroup = mArray[0].toString() + ".id";
System.out.println("Group selected -> " + filterGroup);
for (int i = 1; i < mArray.length; i++) {
System.out.println("Value -> " + mArray[i]);
}
String pFilter = null;
for (int i = 1; i < mArray.length; i++) {
/*
*
* This is where I need to change value in
* pos i with i + 1
*
*/
switch (mArray[i].toString()) {
case "0":
mArray[i] = "1";
break;
case "1":
mArray[i] = "2";
break;
case "2":
mArray[i] = "3";
break;
case "3":
mArray[i] = "4";
break;
case "4":
mArray[i] = "5";
break;
case "5":
mArray[i] = "6";
break;
case "6":
mArray[i] = "7";
break;
case "7":
mArray[i] = "8";
break;
case "8":
mArray[i] = "9";
break;
case "9":
mArray[i] = "10";
break;
case "10":
mArray[i] = "11";
break;
case "11":
mArray[i] = "12";
break;
case "12":
mArray[i] = "13";
break;
}
if (mArray.length == 2){
pFilter = mArray[i].toString();
} else {
if (mArray[i] != mArray[mArray.length - 1]) {
if (pFilter != null) {
pFilter = pFilter + mArray[i].toString() + ",";
} else {
pFilter = mArray[i].toString() + ",";
}
} else {
pFilter = pFilter + mArray[i].toString();
}
}
}
String mFilter = "[" + pFilter + "]";
System.out.println("Insert value in a string -> " + mFilter);
String tempParam = null;
if (filterGroup.equals("assignee")) {
tempParam = "{\"$eq\":" + mFilter + "}";
} else {
tempParam = "{\"$in\":" + mFilter + "}";
}
//Override the value with the same filterGroup
if (filterMap.containsKey(filterGroup)) {
String toOverride = filterGroup;
filterMap.remove(filterGroup);
filterMap.put(toOverride, tempParam);
} else {
filterMap.put(filterGroup, tempParam);
}
//iterate
for (Map.Entry<String, String> entry : filterMap.entrySet()) {
switch (entry.getKey()) {
case "status.id":
status = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "queue.id":
queues = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "type.id":
types = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "severity.id":
severities = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "assignee.id":
mytickets = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
}
}
filterMapValues = parameters ;
if (status != null) {
filterMapValues += ", " + status;
}
if (queues != null) {
filterMapValues += ", " + queues;
}
if (types != null) {
filterMapValues += ", " + types;
}
if (severities != null) {
filterMapValues += ", " + severities;
}
if (mytickets != null) {
filterMapValues += ", " + mytickets;
}
String myFilter = "{" + filterMapValues + "}";
System.out.println("myFilter -> " + myFilter);
//setup request header
con.setRequestProperty("X-Filter", myFilter);
} else {
String xFilter = "{\"status.id\":" + statusAll + ", \"queue.id\":" + queueAll + ", \"type.id\":" + typeAll + ", \"severity.id\":" + severityAll + "," + parameters + "}";
con.setRequestProperty("X-Filter", xFilter);
System.out.println("Reset all -> " + xFilter);
}
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + mUrl);
System.out.println("Response Code : " + responseCode);
mStreamResponse = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(mStreamResponse));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
mStreamResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mString = sb.toString();
} catch (Exception e) {
}
return mString;
}
How can I do?
Thanks in advance.
Edit
I started the for loop in pos #1 because in pos #0 I save filterGroup value, and that's a String, I need to menage as int only values in pos > 0
First off:
I'd like to convert an ArrayList to integer [...]
ArrayList<E> is a collection object with type E that can be any object or primitive. What you are really asking for is how to convert an ArrayList<String> (see that it is an ArrayList of type String) into an integer array. I can see you have already converted the ArrayList<String> into an Object[] (Object array that can hold both integers and Strings) using the following line in the example code given above:
Object[] mArray = filter.toArray();
Getting back to the original answer, this would do it:
int[] mArray = new int[filter.size()];
for (int i = 0; i < filter.size(); i++) {
int value = Integer.parseInt(filter.get(i));
mArray[i] = value++;
}
Your code is correct just change the for loop initial value to start from 0 rather than 1 like this:
int tempValue = 0;
for (int i = 0; i < mArray.length; i++) {
{
// increasing your mArray value
tempValue = (Integer) mArray[i] + 1;
mArray[i] = tempValue;
//Rest of your code
}
Can you try this please.
Remove your switch case inside for and replace it with below. Hope you want something like this.
for(int i=0; i<mArray.length(); i++){
mArray[i] = i+1;
}
let me know..
Do follwoing
Step 1: Create a method
private List<Integer> stringToIncrementedString(ArrayList<String> stringArrayList){
List<Integer> arrayInt;
arrayInt = new ArrayList<Integer>();
for(int i=1 ;i<stringArrayList.size();i++)
arrayInt.add(Integer.parseInt(stringArrayList.get(i))+1);
return arrayInt;
}
Step 2 :Call this method from where you want.It will return the Arraylist with incremented value.

JSON remove special characters

I want to do the replication between Android sqlite & MS SQL server.That Time i want to take Tables values from Databse.
This is my JSON
{
"Table1":[
{
"BusinessUnit":"MASS",
"ProductCode":"SLD0201",
"Description":"Lou Difan C.Blue 12"3- Commode",
"Description2":"301 0201"
},
{
"BusinessUnit":"MASS",
"ProductCode":"SLN0502",
"Description":"Lou Napoli I"vory- Cistern",
"Description2":"2011 0502"
},
{
"BusinessUnit":"MASS",
"ProductCode":"LDMBL6H",
"Description":"Dortek Taper Bullet Handle 6"5 serr ",
"Description2":"Taper Bullet Ha"
}
],
"Table2":[
{
"chk":6,
"currentchk":1
}
]
}
In Here JSON Description column value contain "(double quotation) .If we check http://jsonformatter.curiousconcept.com/ , it show error.Its a Invalid JSON.
WCF service I have converted DataSet to JSON. Some table column contain special charters.
I converted like this :
public String ConverTableToJson(DataSet dsDownloadJson,int currentSplit)
{
StringBuilder Sb = new StringBuilder();
String result = "";
int start = 0;
int end =500;
int chk = 0;
int currentChk = currentSplit;
if (dsDownloadJson.Tables.Count > 0)
{
Sb.Append("{");
foreach (DataTable dt in dsDownloadJson.Tables)
{
DataTable dtDownloadJson = dt;
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
double total = dtDownloadJson.Rows.Count;
Console.WriteLine("--1--" + dtDownloadJson.Rows.Count);
if (dtDownloadJson.Rows.Count < 500)
{
end = dtDownloadJson.Rows.Count;
}
if (chk == 0)
{
if (dtDownloadJson.Rows.Count > 500)
{
if ((dtDownloadJson.Rows.Count / 500) == 0)
{
chk = dtDownloadJson.Rows.Count / 500;
}
else
{
chk = dtDownloadJson.Rows.Count / 500 + 1;
}
}
else
{
chk = 1;
}
currentChk = 1;
}
else
{
currentChk = currentChk + 1;
start = currentChk * 500;
end = start + 500;
currentChk = chk;
}
Sb.Append("\"" + dtDownloadJson.TableName + "1\" : [");
if (dtDownloadJson.Rows.Count > 0)
{
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
Console.WriteLine("--2--" + start);
Console.WriteLine("--3--" + end);
for (int i = start; i < end; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
TempStr = TempStr.Replace(""", '\"');
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
}
}
else
{
}
Sb.Append("],");
if (chk > 1)
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
else
{
Sb.Append("\"Table2\": [{\"chk\": " + chk + ", \"currentchk\": " + currentChk + " }]");
}
}
// Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("}");
return Sb.ToString();
}
else
{
return "0";
}
}
My problem is removing special charters OR How to allow special characters.?
Please help me anybody...
You shouldn't use a StringBuilder to convert an object to a JSON string. Use the JsonConverter class in JayRock JSON library and it takes care of Serialising/Deserialising Json for you (including escaping)
try to use inbuilt json serialization
public static string Serialize<T>(T obj)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new
System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.Default.GetString(ms.ToArray());
ms.Dispose();
return retVal;
}

Categories

Resources