I'm querying my calendar and showing all events result.
When i'm trying to parse the value CalendarContract.Events.DURATION i'm getting a RFC2445 string format.
For example i'm getting "P15M" which I know it's 15 minutes meeting.
After digging on the internet on how to parse RFC2445 I've found some google jar here
But is there any static class to parse those format?
Compiling a jar and using it only for 1 function it's not that nice...
Thanks for the help
I have had the same problem as you, dug around and found the following useful snippet somewhere. I refactored it a bit, so it will be more readable. hope it helps!
public static long RFC2445ToMilliseconds(String str)
{
if(str == null || str.isEmpty())
throw new IllegalArgumentException("Null or empty RFC string");
int sign = 1;
int weeks = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
int len = str.length();
int index = 0;
char c;
c = str.charAt(0);
if (c == '-')
{
sign = -1;
index++;
}
else if (c == '+')
index++;
if (len < index)
return 0;
c = str.charAt(index);
if (c != 'P')
throw new IllegalArgumentException("Duration.parse(str='" + str + "') expected 'P' at index="+ index);
index++;
c = str.charAt(index);
if (c == 'T')
index++;
int n = 0;
for (; index < len; index++)
{
c = str.charAt(index);
if (c >= '0' && c <= '9')
{
n *= 10;
n += ((int)(c-'0'));
}
else if (c == 'W')
{
weeks = n;
n = 0;
}
else if (c == 'H')
{
hours = n;
n = 0;
}
else if (c == 'M')
{
minutes = n;
n = 0;
}
else if (c == 'S')
{
seconds = n;
n = 0;
}
else if (c == 'D')
{
days = n;
n = 0;
}
else if (c == 'T')
{
}
else
throw new IllegalArgumentException ("Duration.parse(str='" + str + "') unexpected char '" + c + "' at index=" + index);
}
long factor = 1000 * sign;
long result = factor * ((7*24*60*60*weeks)
+ (24*60*60*days)
+ (60*60*hours)
+ (60*minutes)
+ seconds);
return result;
}
In while loop of cursor
String duration = "your duration";
try {
Duration d = new Duration();
d.parse(duration);
endMillis = startMillis + d.getMillis();
if (debug)
Log.d(TAG, "startMillis! " + startMillis);
if (debug)
Log.d(TAG, "endMillis! " + endMillis);
if (endMillis < startMillis) {
continue;
}
} catch (DateException e) {
if (debug)
Log.d(TAG, "duration:" + e.toString());
continue;
}
The class Duration is and also refer line number 1487. there is parsing logic , you just need to include duration class in your source code and parse as in try block.
I hope it helps
Related
This question was migrated from Android Enthusiasts Stack Exchange because it can be answered on Stack Overflow.
Migrated 22 days ago.
I'm having a hard time trying to get /system/bin/raccoon to log the variables being sent to it through the control socket. I can get it to log with any variables sent to the command line just fine but when I try to use an external app sending the variables to /dev/socket/raccoon I can't see them. What am I doing wrong? Below is the code. Thanks in advance
My logging code
FILE *filepntr = fopen("/sdcard/log.txt", "w");
fprintf(filepntr, "\nThis line was for shits and giggles");
fprintf(filepntr, "*argc: %d\n", *argc );
fprintf(filepntr, "*argv[0]: %s\n", *argv[0] );
if ( *argc == 1 ) {
fprintf(filepntr, "No arguments were passed.\n" );
} else {
fprintf(filepntr, "Arguments:\n" );
for ( i = 1; i < *argc; ++i ) {
fprintf(filepntr, " %d. %s\n", i, *argv[i] );
}
}
Below is the app code:
static int android_get_control_and_arguments(int *argc, char ***argv)
{
static char *args[32];
int control;
int i;
atexit(notify_death);
if ((i = android_get_control_socket("racoon")) == -1) {
return -1;
}
do_plog(LLV_DEBUG, "Waiting for control socket");
if (listen(i, 1) == -1 || (control = accept(i, NULL, 0)) == -1) {
do_plog(LLV_ERROR, "Cannot get control socket");
exit(1);
}
close(i);
fcntl(control, F_SETFD, FD_CLOEXEC);
args[0] = (*argv)[0];
for (i = 1; i < 32; ++i) {
unsigned char bytes[2];
if (recv(control, &bytes[0], 1, 0) != 1 ||
recv(control, &bytes[1], 1, 0) != 1) {
do_plog(LLV_ERROR, "Cannot get argument length");
exit(1);
} else {
int length = bytes[0] << 8 | bytes[1];
int offset = 0;
if (length == 0xFFFF) {
break;
}
args[i] = malloc(length + 1);
while (offset < length) {
int n = recv(control, &args[i][offset], length - offset, 0);
if (n > 0) {
offset += n;
} else {
do_plog(LLV_ERROR, "Cannot get argument value");
exit(1);
}
}
args[i][length] = 0;
}
}
do_plog(LLV_DEBUG, "\n*Received %s Arguments");
*argc = i;
*argv = args;
return control;
}
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.
Is there any pdf text extractor api that extract arabic text from pdf.
I am using itextpdf api it works fine in extract English but it doesn't extract arabic text.
This is my code for extract text in pdf:
private String extractPDF(String path) throws IOException {
String parsedText = "";
PdfReader reader = new PdfReader(path);
int n = reader.getNumberOfPages();
for (int page = 0; page < n; page++) {
parsedText = parsedText + PdfTextExtractor.getTextFromPage(reader, page + 1).trim() + "\n"; //Extracting the content from the different pages
}
reader.close();
return parsedText;
}
and this is the input pdf :arabic.pdf
Update :
i able to extract arabic text but it doesn't preserves the order of the lines , and this is my code:
private String extractPDF(String name) throws IOException {
PdfReader reader = new PdfReader(name);
StringBuilder text = new StringBuilder();
for (int i=1;i<=reader.getNumberOfPages();i++){
String data = PdfTextExtractor.getTextFromPage(reader,i,new SimpleTextExtractionStrategy());
text.append(Bidi.BidiText(data,1).getText());
}
return text.toString();
}
pdf text is :
بسم الله الرحمن الرحيم
السلام عليكم ورحمة الله وبركاته
سبحان الله
the output is :
سبحان الله
السلام عليكم ورحمة الله وبركاته
بسم الله الرحمن الرحيم
this is my code for method BidiText:
public static BidiResult BidiText(String str, int startLevel)
{
boolean isLtr = true;
int strLength = str.length();
if (strLength == 0)
{
return new BidiResult(str, false);
}
// get types, fill arrays
char[] chars = new char[strLength];
String[] types = new String[strLength];
String[] oldtypes = new String[strLength];
int numBidi = 0;
for (int i = 0; i < strLength; ++i)
{
chars[i] = str.charAt(i);
char charCode = str.charAt(i);
String charType = "L";
if (charCode <= 0x00ff)
{
charType = BaseTypes[charCode];
}
else if (0x0590 <= charCode && charCode <= 0x05f4)
{
charType = "R";
}
else if (0x0600 <= charCode && charCode <= 0x06ff)
{
charType = ArabicTypes[charCode & 0xff];
}
else if (0x0700 <= charCode && charCode <= 0x08AC)
{
charType = "AL";
}
if (charType.equals("R") || charType.equals("AL") || charType.equals("AN"))
{
numBidi++;
}
oldtypes[i] = types[i] = charType;
}
if (numBidi == 0)
{
return new BidiResult(str, true);
}
if (startLevel == -1)
{
if ((strLength / numBidi) < 0.3)
{
startLevel = 0;
}
else
{
isLtr = false;
startLevel = 1;
}
}
int[] levels = new int[strLength];
for (int i = 0; i < strLength; ++i)
{
levels[i] = startLevel;
}
String e = IsOdd(startLevel) ? "R" : "L";
String sor = e;
String eor = sor;
String lastType = sor;
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("NSM"))
{
types[i] = lastType;
}
else
{
lastType = types[i];
}
}
lastType = sor;
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("EN"))
{
types[i] = (lastType.equals("AL")) ? "AN" : "EN";
}
else if (t.equals("R") || t.equals("L") || t.equals("AL"))
{
lastType = t;
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("AL"))
{
types[i] = "R";
}
}
for (int i = 1; i < strLength - 1; ++i)
{
if (types[i].equals("ES") && types[i - 1].equals("EN") && types[i + 1].equals("EN"))
{
types[i] = "EN";
}
if (types[i].equals("CS") && (types[i - 1].equals("EN") || types[i - 1].equals("AN")) && types[i + 1] == types[i - 1])
{
types[i] = types[i - 1];
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("EN"))
{
// do before
for (int j = i - 1; j >= 0; --j)
{
if (!types[j].equals("ET"))
{
break;
}
types[j] = "EN";
}
// do after
for (int j = i + 1; j < strLength; --j)
{
if (!types[j].equals("ET"))
{
break;
}
types[j] = "EN";
}
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("WS") || t.equals("ES") || t.equals("ET") || t.equals("CS"))
{
types[i] = "ON";
}
}
lastType = sor;
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (t.equals("EN"))
{
types[i] = (lastType.equals("L")) ? "L" : "EN";
}
else if (t.equals("R") || t.equals("L"))
{
lastType = t;
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("ON"))
{
int end = FindUnequal(types, i + 1, "ON");
String before = sor;
if (i > 0)
{
before = types[i - 1];
}
String after = eor;
if (end + 1 < strLength)
{
after = types[end + 1];
}
if (!before.equals("L"))
{
before = "R";
}
if (!after.equals("L"))
{
after = "R";
}
if (before == after)
{
SetValues(types, i, end, before);
}
i = end - 1; // reset to end (-1 so next iteration is ok)
}
}
for (int i = 0; i < strLength; ++i)
{
if (types[i].equals("ON"))
{
types[i] = e;
}
}
for (int i = 0; i < strLength; ++i)
{
String t = types[i];
if (IsEven(levels[i]))
{
if (t.equals("R"))
{
levels[i] += 1;
}
else if (t.equals("AN") || t.equals("EN"))
{
levels[i] += 2;
}
}
else
{
if (t.equals("L") || t.equals("AN") || t.equals("EN"))
{
levels[i] += 1;
}
}
}
int highestLevel = -1;
int lowestOddLevel = 99;
int ii = levels.length;
for (int i = 0; i < ii; ++i)
{
int level = levels[i];
if (highestLevel < level)
{
highestLevel = level;
}
if (lowestOddLevel > level && IsOdd(level))
{
lowestOddLevel = level;
}
}
for (int level = highestLevel; level >= lowestOddLevel; --level)
{
int start = -1;
ii = levels.length;
for (int i = 0; i < ii; ++i)
{
if (levels[i] < level)
{
if (start >= 0)
{
chars = ReverseValues(chars, start, i);
start = -1;
}
}
else if (start < 0)
{
start = i;
}
}
if (start >= 0)
{
chars = ReverseValues(chars, start, levels.length);
}
}
String result = "";
ii = chars.length;
for (int i = 0; i < ii; ++i)
{
char ch = chars[i];
if (ch != '<' && ch != '>')
{
result += ch;
}
}
return new BidiResult(result, isLtr);
}
Your example PDF does not contain any text at all, it merely contains an embedded bitmap image of text.
When talking about "text extraction from PDFs" (and "text extractor APIs" and PdfTextExtractor classes etc.), one usually means finding text drawing instructions in the PDF (for which a PDF viewer uses a font program either embedded in the PDF or available on the system at hand to display the text) and determining their text content from their string arguments and font encoding definitions.
As in your case there are no such text drawing instructions, merely a bitmap drawing instruction and the bitmap itself, text extraction from your document will return an empty string.
To retrieve the text displayed in your document, you have to look for OCR (optical character recognition) solutions. PDF libraries (like iText) can help you to extract the embedded bitmap image to forward to the OCR solution if the OCR solution does not directly support PDF but only bitmap formats.
If you also have PDF documents which display Arabic text using text drawing instructions with sufficient encoding information instead of bitmaps, you may need to post-process the text extraction output of iText with a method like Convert as proposed in this answer as pointed out by Amedee in a comment to your question. (Yes, it is written in C# but it is pretty easy to port to Java.)
How to compare app version in android
I got latest version code and current version code , but the problem is
current version is 1.0
and latest version is 1.0.0
so how to compare that float value in android
I have written a small Android library for comparing version numbers: https://github.com/G00fY2/version-compare
What it basically does is this:
public int compareVersions(String versionA, String versionB) {
String[] versionTokensA = versionA.split("\\.");
String[] versionTokensB = versionB.split("\\.");
List<Integer> versionNumbersA = new ArrayList<>();
List<Integer> versionNumbersB = new ArrayList<>();
for (String versionToken : versionTokensA) {
versionNumbersA.add(Integer.parseInt(versionToken));
}
for (String versionToken : versionTokensB) {
versionNumbersB.add(Integer.parseInt(versionToken));
}
final int versionASize = versionNumbersA.size();
final int versionBSize = versionNumbersB.size();
int maxSize = Math.max(versionASize, versionBSize);
for (int i = 0; i < maxSize; i++) {
if ((i < versionASize ? versionNumbersA.get(i) : 0) > (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return 1;
} else if ((i < versionASize ? versionNumbersA.get(i) : 0) < (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return -1;
}
}
return 0;
}
This snippet doesn't offer any error checks or handling. Beside that my library also supports suffixes like "1.2-rc" > "1.2-beta".
I am a bit late to the party but I have a great solution for all of you!
1. Use this class:
public class VersionComparator implements Comparator {
public boolean equals(Object o1, Object o2) {
return compare(o1, o2) == 0;
}
public int compare(Object o1, Object o2) {
String version1 = (String) o1;
String version2 = (String) o2;
VersionTokenizer tokenizer1 = new VersionTokenizer(version1);
VersionTokenizer tokenizer2 = new VersionTokenizer(version2);
int number1, number2;
String suffix1, suffix2;
while (tokenizer1.MoveNext()) {
if (!tokenizer2.MoveNext()) {
do {
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
if (number1 != 0 || suffix1.length() != 0) {
// Version one is longer than number two, and non-zero
return 1;
}
}
while (tokenizer1.MoveNext());
// Version one is longer than version two, but zero
return 0;
}
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number1 < number2) {
// Number one is less than number two
return -1;
}
if (number1 > number2) {
// Number one is greater than number two
return 1;
}
boolean empty1 = suffix1.length() == 0;
boolean empty2 = suffix2.length() == 0;
if (empty1 && empty2) continue; // No suffixes
if (empty1) return 1; // First suffix is empty (1.2 > 1.2b)
if (empty2) return -1; // Second suffix is empty (1.2a < 1.2)
// Lexical comparison of suffixes
int result = suffix1.compareTo(suffix2);
if (result != 0) return result;
}
if (tokenizer2.MoveNext()) {
do {
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number2 != 0 || suffix2.length() != 0) {
// Version one is longer than version two, and non-zero
return -1;
}
}
while (tokenizer2.MoveNext());
// Version two is longer than version one, but zero
return 0;
}
return 0;
}
// VersionTokenizer.java
public static class VersionTokenizer {
private final String _versionString;
private final int _length;
private int _position;
private int _number;
private String _suffix;
private boolean _hasValue;
VersionTokenizer(String versionString) {
if (versionString == null)
throw new IllegalArgumentException("versionString is null");
_versionString = versionString;
_length = versionString.length();
}
public int getNumber() {
return _number;
}
String getSuffix() {
return _suffix;
}
public boolean hasValue() {
return _hasValue;
}
boolean MoveNext() {
_number = 0;
_suffix = "";
_hasValue = false;
// No more characters
if (_position >= _length)
return false;
_hasValue = true;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c < '0' || c > '9') break;
_number = _number * 10 + (c - '0');
_position++;
}
int suffixStart = _position;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c == '.') break;
_position++;
}
_suffix = _versionString.substring(suffixStart, _position);
if (_position < _length) _position++;
return true;
}
}
}
2. create this function
private fun isNewVersionAvailable(currentVersion: String, latestVersion: String): Boolean {
val versionComparator = VersionComparator()
val result: Int = versionComparator.compare(currentVersion, latestVersion)
var op = "=="
if (result < 0) op = "<"
if (result > 0) op = ">"
System.out.printf("%s %s %s\n", currentVersion, op, latestVersion)
return if (op == ">" || op == "==") {
false
} else op == "<"
}
3. and just call it by
e.g. isNewVersionAvailable("1.2.8","1.2.9") where 1.2.8 is your current version here and 1.2.9 is the latest version, which returns true!
Why overcomplicate this so much?
Just scale the major, minor, patch version and you have it covered:
fun getAppVersionFromString(version: String): Int { // "2.3.5"
val versions = version.split(".") // [2, 3, 5]
val major = versions[0].toIntOrDefault(0) * 10000 // 20000
val minor = versions[1].toIntOrDefault(0) * 1000 // 3000
val patch = versions[2].toIntOrDefault(0) * 100 // 500
return major + minor + patch // 2350
}
That way when you compare e.g 9.10.10 with 10.0.0 the second one is greater.
Use the following method to compare the versions number:
Convert float to String first.
public static int versionCompare(String str1, String str2) {
String[] vals1 = str1.split("\\.");
String[] vals2 = str2.split("\\.");
int i = 0;
// set index to first non-equal ordinal or length of shortest version string
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++;
}
// compare first non-equal ordinal number
if (i < vals1.length && i < vals2.length) {
int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
return Integer.signum(diff);
}
// the strings are equal or one string is a substring of the other
// e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
return Integer.signum(vals1.length - vals2.length);
}
Refer the following SO question : Efficient way to compare version strings in Java
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;
}