在java中把xml文件转换成json格式
1、前提需要jar包:
json-lib-2.4-jdk15.jar 和 xom-1.2.5.jar ,maven 仓库:
.sf.json-lib
json-lib
2.4
jdk15
xom
xom
1.2.5
2、代码部分:
public static JSON xmlToJson(String xml) {
XMLSerializer xmlSerializer = new XMLSerializer()
if(xml!=null &&!”“.equals(xml)){
xml = xml.replaceAll(“\r|\n”, “”)
JSON json = xmlSerializer.read(xml)
return json
}else{
return null
}
}
public static void main(String[] args) {
String xmlStr = "01marry"
JSON json = xmlToJson(xmlStr)
System.out.println(json.toString())
}
3、结果:
{“id”:”01”,”name”:”marry”}
2. 把xml格式的字符串转换成json
To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument()
doc.LoadXml(xml)
string jsonText = JsonConvert.SerializeXmlNode(doc)
To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json)
XmlNote myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString)
or .DeserilizeXmlNode(myJsonString, "root")
if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode)
XmlDictionaryReader reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(xml), XmlDictionaryReaderQuotas.Max)
XmlDocument xdoc = new XmlDocument()
xdoc.Load(reader)
3. xml文件怎么解析成json
org.jsonjson 20171018 import org.json.JSONObjectimport org.json.XMLpublic class Main {public static int PRETTY_PRINT_INDENT_FACTOR = 4public static String TEST_XML_STRING ="<?xml version=\"1.0\" ?>Turn this to JSON "public static void main(String[] args) {try {JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING)String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR)System.out.println(jsonPrettyPrintString)} catch (JSONException je) {System.out.println(je.toString())}}}。
引入using Newtonsoft.Json数据查询后填充到DataTable ,再转 JsonConvert.SerializeObject
简单例宴卖毕子:晌芹
DataTable dt = new DataTable()
DataColumn dcName = new DataColumn("Name")
DataColumn dcAge = new DataColumn("Age")
DataColumn dcCity = new DataColumn("City")
dt.Columns.Add(dcName)
dt.Columns.Add(dcAge)
dt.Columns.Add(dcCity)
for (int i = 0i <配散 10i++)
{
DataRow dr = dt.NewRow()
dr[0] = "Name" + i
dr[1] = "Age" + i
dr[2] = "City" + i
dt.Rows.Add(dr)
}
json = JsonConvert.SerializeObject(dt)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)