Ignore namespace attributes while serializing xml data to json - json

I am trying to serialize xml directly to json using JsonSerializer() but the namespace attributes are getting added as fields in the final json. Any suggestion on how to remove this? I tried with JsonConvert.Serialize() but some childnodes are missing in the serialized json.

A solution to your problem could be to deserialize your object to a dictionary first. This way you can add some logic in between the conversion to it.
Check the example below:
var xml = #"<?xml version='1.0' standalone='no'?>
<root>
<person id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
</person>
<person id='2'>
<name>Louis</name>
<url>http://www.yahoo.com</url>
</person>
</root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var childNodeList = doc.DocumentElement.ChildNodes;
for (int i = 0; i < childNodeList.Count; i++)
{
var nodes = childNodeList.Item(i).ChildNodes;
var dict = new Dictionary<string, object>();
foreach (XmlNode node in nodes)
{
var serializedNode = JsonConvert.SerializeXmlNode(node);
var prop = JsonConvert.DeserializeObject<IDictionary<string, object>>(serializedNode).FirstOrDefault();
dict.Add(prop.Key, prop.Value ?? " ");
}
Console.WriteLine($"item {i}");
Console.WriteLine(string.Join("\r\n", dict.Select(e => $"{e.Key}: {e.Value}")));
}
Output:
//item 0
//name: Alan
//url: http://www.google.com
//item 1
//name: Louis
//url: http://www.yahoo.com

Related

How to remove list square brackets from serialized json string

I'm calling a stored procedure using a controller.
var insert_query = entities.Database.SqlQuery<Call_Info>("exec [dbo].[insert_call_info] #call_id",
new SqlParameter("call_id", call_id)).ToList();
jsonResult = JsonConvert.SerializeObject(insert_query); // <-- using Newtonsoft.Json
The json string is the following:
"[{\"call_info_id\":18,\"call_id\":91389,\"user_id\":\"105bdbfb-d65a-42d3-ac79-c1e2575ed243\",\"call_arrive\":\"2020-04-03T21:51:24.797\",\"call_end\":\"2020-04-03T22:04:24.797\",\"info\":\"test\",\"AspNetUser\":null,\"Call\":null,\"StatusCode\":1}]"
Is there a way to remove the [ and ] brackets?
I want the json string to be:
{\"call_info_id\":18,\"call_id\":91389,\"user_id\":\"105bdbfb-d65a-42d3-ac79-c1e2575ed243\",\"call_arrive\":\"2020-04-03T21:51:24.797\",\"call_end\":\"2020-04-03T22:04:24.797\",\"info\":\"test\",\"AspNetUser\":null,\"Call\":null,\"StatusCode\":1}
var insert_query = entities.Database.SqlQuery<Call_Info>("exec [dbo].[insert_call_info] #call_id",
new SqlParameter("call_id", call_id)).ToList();
if(insert_query!=null && insert_query.Count()>0)
{
jsonResult = JsonConvert.SerializeObject(insert_query[0]);
}
This will serialise only 1st element so it wont have []

QT - Parse XML with html reference notation of umlauts

I hope anybody can help me.
My problem is that I get XML with html entities for special charakters like:
<person>
<firstname>Max</firstname>
<lastname>Müller</lastname>
</person>
<person>
<firstname>Bernd</firstname>
<lastname>Schäfer</lastname>
</person>
I find no way in QT to decode the "&uuml" to a normal "ü". In the QT-DomTree this entity will stand in a QDomEntityRefrence object wich has no getter or other output or parse functionality.
I use standard way to parse the XML tree
QDomDocument doc;
if (!doc.setContent(response, &errors))
return false;
QDomElement const & root = doc.firstChildElement("person");
for (QDomElement xmlPerson= root.firstChildElement("person"); !xmlPerson.isNull(); xmlPerson = xmlPerson.nextSiblingElement("person"))
{
QDomNodeList personCont = xmlPerson.childNodes();
PersonObj person;
for(int i = 0; i < personCont.count(); i++)
{
QDomNode itemNode = personCont.at(i);
if(itemNode.isElement()){
QDomElement item = itemNode.toElement();
if(item.tagName() == "firstname")
{
person.setFirstname(item.firstChild().text());
}
else if(item.tagName() == "lastname")
{
addressBook.setLastname(item.firstChild().text());
}
...
Result:
Max Mller
Bernd Schfer
Thanks for your greate awnsers
Use QTextDocument()
QTextDocument doc;
doc.setHtml("Schäfer");
qDebug()<<doc.toPlainText();
In your example
QTextDocument doc;
switch(item.tagName())
{
case "firstname":
doc.setHtml(item.firstChild().text());
person.setFirstname(doc.toPlainText());
break;
case "lastname":
doc.setHtml(item.firstChild().text());
addressBook.setLastname(doc.toPlainText());
break;
...

Not able to send json object to servlet

Here i am calling servlet through AJAX Call from JSP.In servlet ,fetching data from DB and Converting these data to JSON Format using Gson.After that i want to send this json object to this JSP.But here i am not able to send json object.Please suggest Me?
Here code for AJAX Call :
<script type="text/javascript">
$(document).ready(function() {
$('#subbtn').click(function(event) {
console.log("Hello");
var searchfield = $('#searchfields').val();
var operator = $('#operator').val();
var fieldvalue = $('#searchstring').val();
var filter=searchfield+operator+"'"+fieldvalue+"'";
console.log(filter);
$.get('SearchData', {
filter : filter
}, function(responseText) {
$('#example').html(responseText);
console.log('dddd');
});
});
});
</script>
Here is servlet COde :
String query = "select * from searchsample";
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
renderingengine = resultSet.getString("RenderingEngine");
browser = resultSet.getString("Browser");
platform = resultSet.getString("platform");
engineversion = resultSet.getString("EngineVersion");
cssgrade = resultSet.getString("CSSGrade");
}
Gson gson = new Gson();
JsonVo jsondata=new JsonVo();
jsondata.setRenderingengine(renderingengine);
jsondata.setBrowser(browser);
jsondata.setPlatform(platform);
jsondata.setEngineversion(engineversion);
jsondata.setCssgrade(cssgrade);
String toJson = gson.toJson(jsondata);
System.out.println("Json Format : " +toJson);
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
I think you just need write below line to send JSON to JSP from servlet.
response.setContentType("application/json");
response.getWriter().write(toJson);

Solr Json parsing on Client Side?

I am trying to retrieve date and corresponding count from a json below and it turns out that I just can't do it. After some struggle, I ended with the weird code below with nested linkedlists. How can I select solr_date and count as appearing at the very end : (I welcome any library that can do this)
{
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"facet":"true",
"fl":" ",
"indent":"true",
"facet.query":" solr_date",
"q":"solr_body:party",
"facet.field":"solr_date",
"json.nl":"arrarr",
"wt":"json",
"fq":" "}},
"response":{"numFound":19,"start":0,"docs":[
{},
{},
{},
{},
{},
{},
{},
{},
{},
{}]
},
"facet_counts":{
"facet_queries":{
" solr_date":0},
"facet_fields":{
"solr_date":
[
["2013-06-19T13:48:02Z",10], *********************************
["2013-07-25T13:48:02Z",2],
["2013-07-27T13:48:02Z",2],
["2013-07-24T13:48:02Z",1], I need these numbers individually. Date and corresponding number.
["2013-07-26T13:48:02Z",1],
["2013-07-28T13:48:02Z",1],
["2013-07-29T13:48:02Z",1],
["2013-07-30T13:48:02Z",1]]}, ***************************
"facet_dates":{},
"facet_ranges":{}}}
Java code below :
ObjectMapper mapper = new ObjectMapper();
// JsonNode rootNode = m.readTree(new URL("http://173.255.245.138:8983/solr/collection1/select?q=*%3A*&wt=json&indent=true"));
Map<String, Object> mapObject = mapper.readValue(new URL("http://ipa.ddr.ess.000:8983/solr/collection1/select?q=solr_body%3Aparty&fq=+++&fl=+&wt=json&json.nl=arrarr&indent=true&facet=true&facet.query=+solr_date&facet.field=solr_date"),new TypeReference<Map<String, Object>>() {});
LinkedHashMap<String,LinkedHashMap<String,LinkedHashMap<String,ArrayList<String>>>> list = (LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, ArrayList<String>>>>) mapObject.get("facet_counts");
I would suggest using the SolrJ Client:
Solrj is a java client to access solr. It offers a java interface to add, update, and query the solr index.
If you're using Gson, and you're actually only interested in the part you highlighted, you could do a manual parsing. Something like this:
//Create parser and get the root object
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
//Get the solr_date array
JsonArray solrDateArray = rootObj
.getAsJsonObject("facet_counts")
.getAsJsonObject("facet_fields")
.getAsJsonArray("solr_date");
//Create arrays to store the data you want to retrieve
List<String> datesList = new ArrayList<>();
List<Integer> countsList = new ArrayList<>();
//Iterate the solr_date array
Iterator<JsonElement> it = solrDateArray.iterator();
while (it.hasNext()) {
//The solr_date array contains in turn arrays, so we parse each
JsonArray array = it.next().getAsJsonArray();
//and store in your Lists the values
datesList.add(array.get(0).getAsString());
countsList.add(array.get(1).getAsInt());
}
Now you'll have to List objects, one with all the dates and another with all the counts:
datesList: ["2013-06-19T13:48:02Z", "2013-07-25T13:48:02Z", 2013-07-27T13:48:02Z, ...]
countsList: [10, 2, 2, ...]
Note: instead of using 2 List objects, you could use a Map<Integer, String> for example...
i did it something like this.
HttpSolrServer server = new HttpSolrServer("http://localhost:8084/apache-solr-3.6.0/");
server.setParser(new XMLResponseParser());
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery("keyword");
solrQuery.setFilterQueries("keyword");
solrQuery.setHighlight(true);
solrQuery.setHighlightRequireFieldMatch(true);
solrQuery.addHighlightField("syndrome");
solrQuery.setStart(0);
solrQuery.setRows(10);
QueryResponse serverResponse = null;
try {
serverResponse = server.query(solrQuery);
} catch (SolrServerException e) {
e.printStackTrace();
}
Gson gson = new Gson();
List<SolrDocument> docs = new ArrayList<SolrDocument>();
for (SolrDocument doc:serverResponse.getResults()) {
docs.add(doc);
}
Map<String, String> pairs= new HashMap<String, String>();
Integer count = new Integer(0);
for (SolrDocument doc:docs){
pairs.put(("start_date" + count), doc.getFieldValue("start_date").toString());
pairs.put(("test_file_result_id" + count), doc.getFieldValue("test_file_result_id").toString());
pairs.put(("job_id" + count), doc.getFieldValue("job_id").toString());
pairs.put(("cluster" + count), doc.getFieldValue("cluster").toString());
pairs.put(("test_file_result_id" + count), doc.getFieldValue("test_file_result_id").toString());
count++;
}

Write output values to a json file using java

Hi below is my code to extract particular metadata tags and write those tags to a json file. And i imported json.lib.jar and tika-app.jar into my build path.
File dir = new File("C:/pdffiles");
File listDir[] = dir.listFiles();
for (int i = 0; i < listDir.length; i++)
{
System.out.println("files"+listDir.length);
String file=listDir[i].toString();
File file1 = new File(file);
InputStream input = new FileInputStream(file1);
Metadata metadata = new Metadata();
BodyContentHandler handler = new BodyContentHandler(10*1024*1024);
AutoDetectParser parser = new AutoDetectParser();
parser.parse(input, handler, metadata);
Map<String, String> map = new HashMap<String, String>();
map.put("File name: ", listDir[i].getName());
map.put("Title: " , metadata.get("title"));
map.put("Author: " , metadata.get("Author"));
map.put("Content type: " , metadata.get("Content-Type"));
JSONObject json = new JSONObject();
json.accumulateAll(map);
FileWriter file2;
file2 = new FileWriter("C:\\test.json");
file2.write(json.toString());
file2.flush();
}
But it is writing only single file metadata to the json file. Is there any problem with my code, please suggest me.
may be you should use-
file2.write(json.toJSONString());
instead of this line -
file2.write(json.toString());