json数据中有些字符串太长,想换行写确不知道怎么去换行,那么接下来,我们就来给大家讲解一下json换行的方法,不会的小伙伴可以参考以下方法!大家觉得文章有用的话,也可以收藏哦!
后台代码把换行符\r\n替换为\\r\\n,前台代码js收到的字符就是\r\n。代码如下:public static string ConvertFromListTojson(IListlist, int total, string columnInfos) where T: class
{
string[] cols = columnInfos.Split(new char[]
{
','
}, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder(300);
sb.Append("{\"total\":");
sb.Append(total);
sb.Append(",\"rows\":");
sb.Append("[");
foreach(T t in list)
{
sb.Append("{");
foreach(string col in cols)
{
string name = "\"{0}\":\"{1}\",";
string value = getValue(t, col);
value = value.Replace("\r\n", "\\r\\n");
sb.Append(string.Format(name, col, value));
}
if (cols.Length > 0)
{
int length = sb.Length;
sb.Remove(length - 1, 1);
}
sb.Append("},");
}
if (list.Count > 0)
{
int length2 = sb.Length;
sb.Remove(length2 - 1, 1);
}
sb.Append("]");
sb.Append("}");
return sb.ToString();
}
private static string getValue(T t, string pname) where T: class
{
Type type = t.GetType();
PropertyInfo pinfo = type.GetProperty(pname);
if (pinfo != null)
{
object v = pinfo.GetValue(t, null);
return v != null ? v.ToString() : "";
}
else
{
throw new Exception("不存在属性" + pname);
}
}
Java读取txt文件换行怎么写?
1. Java读取txt文件package com.campu;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* H20121012.java
*/
public class H20121012
{
public static void readTxtFile(String filePath)
{
try
{
String encoding = "GBK";
File file = new File(filePath);
if (file.isFile() && file.exists())
{ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding); //考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null)
{
System.out.println(lineTxt);
}
read.close();
}
else
{
System.out.println("找不到指定的文件");
}
}
catch (Exception e)
{
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
public static void main(String argv[])
{
String filePath = "L:\\Apache\\htdocs\\res\\20121012.txt";
// "res/";
readTxtFile(filePath);
}
}
2.不同操作系统换行写txt文件
针对常用的系统,可以使用如下的转义符实现换行:
windows下的文本文件换行符:\r\n
linux/unix下的文本文件换行符:\r
Mac下的文本文件换行符:\n
(1)使用java中的转义符"\r\n":
String str="aaa";
str+="\r\n";
(2)BufferedWriter的newline()方法:
FileOutputStream fos=new FileOutputStream("c;\\11.txt");
BufferedWriter bw=new BufferedWriter(fos);
bw.write("你好");
bw.newline();
bw.write("java");
w.newline();
json换行的方法大家可参考以上内容,另外,本文也分享了
Java读取txt文件换行写txt文件的方法,希望也能给大家带来帮助哦!最后大家如果想要了解更多json工具教程知识,敬请关注奇Q工具网。
推荐阅读: