odd result converting XML to JSON - json

I get an odd result when converting XML to JSON. I am using JsonConvert.SerializeXmlNode():
XmlNodeList requestNode = xmlDocument.GetElementsByTagName("root","*");
XmlNode objNode = requestNode[0];
string json = JsonConvert.SerializeXmlNode(objNode);
If my nodes include a namespace prefix and URL, the JsonConvert.SerializeXmlNode comes back with odd looking JSON having attributes like :
{"prefix:Amount":{"#xmlns:prefix":"http://BLA","#text":"1000"}}.
I expect :
{"prefix:Amount": 100, etc etc.}
The XML am trying to convert looks something like:
<a:root>
<prefix:Amount xmlns:prefix="http://BLA>1000</prefix:Amount>
</a:root>

Your XML is not well-formed: xmlns:prefix="http://BLA is missing a closing quote.

Related

Enumerating of JObject of NewtonSoft.Json loses '\' character in C#

I would like to parse json string using JObject.Parse() of NewtonSoft.Json. Assume that the json string is like this:
{"json":"{\"count\":\"123\"}"}
The result of jObject.First.ToString() is "json": "{\"count\":\"123\"}".
The result of jObject["json"].ToString() is {"count":"123"}. Enumerating gets the same result as this.
The testing code I used is like this.
[TestMethod()]
public void JsonParseTest()
{
var json = "{\"json\":\"{\\\"count\\\":\\\"123\\\"}\"}";
var jObject = JObject.Parse(json);
Console.WriteLine($"json : {json}");
Console.WriteLine($"jObject.First.ToString() : {jObject.First}");
Console.WriteLine($"jObject[\"json\"].ToString() : {jObject["json"]}");
}
We can see that enumerating of jObject will lose the character '\'. What is the problem? I would be appreciated for any suggestion :)
EDIT 1
The version of NewtonSoft is 12.0.3 released in 2019.11.09.
The parser isn't loosing anything. There is no literal \ in your example. The backslashes are purely part of the JSON syntax to escape the " inside the string vlue. The value of the key json is {"count":"123"}.
If you want to have backslashes in that value (however I don't see why you would want that), then you need add them, just like you added them in your C# string (C# and JSON happen to have the same escaping mechanism):
{"json":"{\\\"count\\\":\\\"123\\\"}"}
with leads to the C# code:
var json = "{\"json\":\"{\\\\\\\"count\\\\\\\":\\\\\\\"123\\\\\\\"}\"}";

Obtain value in json response

How do i write an expression to obtain the value "lastUpdated" in the below json response data
{"resourceType":"Parameters","parameter":[{"name":"medication","resource":{"resourceType":"Bundle","id":"956ffe6a-08ed-4cb6-82ca-41065a4a9923","meta":{"lastUpdated":"2020-08-24T19:09:18.5649325+00:00",
I have tried this but it does not work:
regex("\"lastUpdated\": \"(.*?)\"").saveAs("lastUpdated")
this also does not work:
jsonPath("$..[?(#.use==\"lastUpdated\")].value").saveAs("lastUpdated"))
Your input is a little cut off but here is what I've got:
myJSONString = '{"resourceType":"Parameters","parameter":[{"name":"medication","resource":{"resourceType":"Bundle","id":"956ffe6a-08ed-4cb6-82ca-41065a4a9923","meta":{"lastUpdated":"2020-08-24T19:09:18.5649325+00:00"}}}]}'
myJSONObject = JSON.parse(myJSONString)
myLastUpdated = myJSONObject.parameter[0].resource.meta.lastUpdated
console.log(myLastUpdated)
Basically you convert it from a json object into a javascript object. Then you can just traverse down the tree to your intended target.

JsonSlurper parsing String containing Json into unexpected format

From a separate system I get a String parameter "messageJson" whose content is in the form:
{"agent1":"smith","agent2":"brown","agent3":{"agent3_1":"jones","agent3_2":"johnson"}}
To use it in my program I parse it with JsonSlurper.
def myJson = new JsonSlurper().parseText(messageJson)
But the resulting Json has the form:
[agent1:smith, agent2:brown, agent3:[agent3_1:jones, agent3_2:johnson]]
Note the square brackets and the lack of double quotes. How can I parse messageJson so that the original structure is kept?
Ok, thanks to the hint by cfrick, I was able to find a solution. In case anyone else has a similar problem, all I needed to do was using JsonOutput in the end to convert the map back to a Json
I.E. :
def myJson = new JsonSlurper().parseText(messageJson)
myJson << [agent4:"jane"]
def backToJson = JsonOutput.toJson(myJson)

Axis2 JSon Support (Jettison) bad xml conversion

I am using Axis2 1.6.4 to implement REST Json WebServices (https://axis.apache.org/axis2/java/core/docs/json_support.html) and I face an issue when Jettison converts Json object To XML if it does not have a "root" element. Details:
If request is:
{"name":"John","age":30}
Then XML OMElement at server side is:
<name>John</name
So age element is missed
Instead, if request is:
{person:{"name":"John","age":30}}
Then XML OMElement at server side is:
<person><name>John</name><age>30</age></person>
Thanks for your help,
Martí
I've founda work around to overcome this JSON->XML conversion issue. Thanks to this post:How to use Axis2 JSON, I've realized I am able to access input json before converting it to XML, and also to create an OMElement from a json string. So when input is a json request, I wrap it with a json "root" element, and then convert it to XML without losing data.
If it could be useful to someone, below is the source code to get input json string and the source code to convert json string to OMElement
Get input json string and wrap into a root
OMSourcedElement source=(OMSourcedElement )msg;
AbstractJSONDataSource jsonSoucre=(AbstractJSONDataSource)source.getDataSource();
MessageContext msgCtxt= MessageContext.getCurrentMessageContext();
JSONDataSource jsonRequestEnvDS= new JSONDataSource(new StringReader("{\"JSONEnvelope\": " + jsonSoucre.getObject() + " }"), msgCtxt);
OMFactory factory = OMAbstractFactory.getOMFactory();
OMSourcedElement omRequest = factory.createOMElement(jsonRequestEnvDS,null,null);
Create an OMElement from a json string
String jsonString="{...}";
JSONDataSource jsonDS= new JSONDataSource(new StringReader(jsonString),msgCtxt);
factory = OMAbstractFactory.getOMFactory();
OMSourcedElement resonseJson = factory.createOMElement(jsonDS,null,null);
return resonseJson;

HtmlAgilityPack The '"' character, hexadecimal value 0x22, cannot be included in a name

This line:
Dim NewHTMLString As String = XDocument.Parse(htmldoc.DocumentNode.OuterHtml).ToString()
Produces this error:
The '"' character, hexadecimal value 0x22, cannot be included in a name.
This is the line in the HTML it says is wrong:
if ( typeof JSON != 'object' || !JSON.stringify || !JSON.parse ) { document.write( "<scr" + "ipt type=\"text\/javascript\" src=\"http:\/\/blahblah"><\/script>\n" ); };
That's because XDocument meant to deal with XML, hence it doesn't support arbitrary Javascript string. XDocument thinks this part : <scr", as beginning of an XML node and double-quote (") character in the XML node name is considered invalid.
I was using XDocument in the answer to your previous question to get beautifully formatted XML output in console, and I did that because I know exactly that my HTML is XML compliant. In this case, your HTML isn't valid from XML point of view and it isn't clear what you're trying to achieve using XDocument here. If you simply need to check result from modification you did to the original HTML, you can either directly print htmldoc.DocumentNode.OuterHtml to console or save the HTML to a new file like so :
htmldoc.Save("path_to_new_file.html")