I have a need to parse JSON in Java from a file that we use in the browser, which contains JavaScript.
When the JSON parser gets to the cb key, and location.protocol, it has an issue and fails.
{
data: {
data1: {
plugins: ['voip', 'speed', 'act', 'capacity'],
last: "~last~",
unit: "~units~",
sid: '~sessionid~',
by: "~by~"
}
},
cb: location.protocol + "//" + location.host,
thresholds: ['default'],
calendars: ['default']
}
Is there any way in Java or the JSON parser to account for this so I can still access the keys I need?
Related
I want to convert XML to JSON using either Java or Scala. Below is the working code, but here I am not able to see any identifier for XML attributes in Json to differentiate it with elements.
I need help to get XML attributes with identifier(#) in Json output.
Input XML :
<Test>
<AttrTest Code="199" Pro="Intel" Version="9.106">
<Info>FD2F</Info>
</AttrTest>
</Test>
Code :
import org.json.XML
def xmlToJson(xml: String) = {
var PRETTY_PRINT_INDENT_FACTOR = 4
try {
val xmlJSONObj = XML.toJSONObject(xml)
val jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR)
jsonPrettyPrintString
} catch {
case ex: Exception =>
println(ex.toString)
}
}
val xmlStr = "<Test>\n\t\t<AttrTest Code=\"199\" Pro=\"Intel\" Version=\"9.106\">\n\t\t<Info>FD2F</Info>\n</AttrTest>\n</Test>\n\t"
println(xmlToJson(xmlStr))
Output :
{"Test": {"AttrTest": {
"Version": 9.106,
"Pro": "Intel",
"Info": "FD2F",
"Code": 199
}}}
Expected Output :
{"Test": {"AttrTest": {
"#Version": 9.106,
"#Pro": "Intel",
"Info": "FD2F",
"#Code": 199
}}}
Please help.
I am afraid it is not possible with the library you are using. Here's from their docs:
Some information may be lost in this transformation because JSON is a data format and XML is a document format. XML uses elements, attributes, and content text, while JSON uses unordered collections of name/value pairs and arrays of values. JSON does not does not like to distinguish between elements and attributes.
You may try looking into other XML->JSON libraries or implement a pre-conversion step that would, say, append a "#" prefix to each node's attribute.
Because of the project requirement, I have to use com.fasterxml.jackson.databind library to parse JSON data cannot use other JSON libraries available.
I am new to JSON parsing, so not sure if there are better options here?
I would like to know how can I update a string value in an Array node in the JSON file.
Following is a sample JSON. Please note this is not the entire file content, it's a simplified version.
{
"call": "SimpleAnswer",
"environment": "prod",
"question": {
"assertions": [
{
"assertionType": "regex",
"expectedString": "(.*)world cup(.*)"
}
],
"questionVariations": [
{
"questionList": [
"when is the next world cup"
]
}
]
}
}
Following is the code to read JSON into java object.
byte[] jsonData = Files.readAllBytes(Paths.get(PATH_TO_JSON));
JsonNode jsonNodeFromFile = mapper.readValue(jsonData, JsonNode.class);
To update a root level node value e.g. environment in the JSON file , I found following approach on some SO threads.
ObjectNode objectNode = (ObjectNode)jsonNodeFromFile;
objectNode.remove("environment");
objectNode.put("environment", "test");
jsonNodeFromFile = (JsonNode)objectNode;
FileWriter file = new FileWriter(PATH_TO_JSON);
file.write(jsonNodeFromFile.toString());
file.flush();
file.close();
QUESTION 1: Is this the only way to update a value in JSON file and is it the best way possible? I'm concerned on double casting and file I/O here.
QUESTION 2: I could not find a way to update the value for a nested Array node e.g. questionList. Update the question from when is the next world cup to when is the next soccer world cup
You can use ObjectMapper to parse that JSON, it is very easy to parse and update JSON using pojo class.
use link to convert your json to java class, just paste your json here n download class structure.
You can access or update nested json field by using . (dot) operator
ObjectMapper mapper = new ObjectMapper();
String jsonString="{\"call\":\"SimpleAnswer\",\"environment\":\"prod\",\"question\":{\"assertions\":[{\"assertionType\":\"regex\",\"expectedString\":\"(.*)world cup(.*)\"}],\"questionVariations\":[{\"questionList\":[\"when is the next world cup\"]}]}}";
TestClass sc=mapper.readValue(jsonString,TestClass.class);
// to update environment
sc.setEnvironment("new Environment");
System.out.println(sc);
//to update assertionType
Question que=sc.getQuestion();
List assertions=que.getAssertions();
for (int i = 0; i < assertions.size(); i++) {
Assertion ass= (Assertion) assertions.get(i);
ass.setAssertionType("New Type");
}
I'm making many HTTP request with JSON Payload and I'm reading one file for every single request to get JSON Payload as below.
postPayload1 = val postPayload = ElFileBody("Test_case1.json")
val TC1 = feed(accountNumberFeeder1)
.exec(http(testCase1).post(appendPathToUrl).headers(common_header).body(postPayload).asJSON
.check(status.is(200)
)
But, it becomes so many JSON files inside my resources directory now. So can I merge all my JSON together in one file as below.
{"testCase1":{
"activationSource": "HH",
"accountStatus": null,
}
}
{"testCase2":{
"activationSource": "HH",
"accountStatus": null,
}
}
and access it with my keys "testCase1", "testCase2" etc ?
val postPayload = ElFileBody("Test_case.json")
From official Gatling Documentation, I found http://gatling.io/docs/2.2.1/session/feeder.html
JSON feeders
Some might want to use data in JSON format instead of CSV:
val jsonFileFeeder = jsonFile("foo.json")
val jsonUrlFeeder = jsonUrl("http://me.com/foo.json")
For example, the following JSON:
[
{
"id":19434,
"foo":1
},
{
"id":19435,
"foo":2
}
]
will be turned into:
record1: Map("id" -> 19434, "foo" -> 1)
record2: Map("id" -> 19435, "foo" -> 2)
Note that the root element has of course to be an array.
I am developing an web application on GWT Framework (JAVA). I am using CouchDB(NoSQL Database)
for storing user profile, user question and answers. I am new in NoSQL Database so i need to implement full text search in my application.
Example : " What is Java ?"
Desired Result : It could be found all the question which have all three words What, is, Java .
So there is any idea how to achieve this result in couchdb.
Use couchdb lucene The integration with couchdb is straightforward and it would be perfect for your use case. Couch-db lucene supports the entire query syntanx of lucene. For your problem the + could be used.
The "+" or required operator requires that the term after the "+" symbol exist somewhere in a the field of a single document.
Here is a sample query
http://localhost:5984/_fti/local/database/_design/design_name/index_name?q=+"What is java"
You can implement it using CouchDB List Functions.
I have a document where I need to search for keywords in name and description field. So, I created a view which will emit doc id as key and doc.name,doc._id,doc.description as value.
Now I created a List function which will use Javascript match function and give me the matching list of doc ids.
Sample Query:
http://localhost:5984/dashboard/_design/testSearch/_list/results/ByName?searchQuery=What is Java
{
"_id": "_design/testSearch",
"lists": {
"results": "function(head, req) { var query= new RegExp(req.query.searchQuery,'i'); var arr=new Array(); var key; var row; while(row = getRow()) { if(row.value[0].match(query) || row.value[2].match(query)) { arr.push([row.value[0].toUpperCase(),row.value[1]]); key = row.key;}} arr.sort(); send('{\"'+key+'\":\"'+arr+'\"}');}"
},
"views": {
"ByName": {
"map": "function (doc) {\n if((doc.isdeleted==\"false\" || doc.isdeleted==false) && doc.userid && doc.name){\n emit(doc._id,[doc.name,doc._id,doc.description]);\n }\n}"
}
},
"language": "javascript"
}
I have a file called wfd.proxy.js that contains the following lines of code :
if (!WFD) { var WFD = {}; };
if (!WFD.Proxy) { WFD.Proxy = {}; };
WFD.Proxy =
{
SERVICE_URL : "/delegate/WFD/WFService?",
PDF_SERVICE_URL : "/delegate/pdf-exporter?",
DATA_TYPE : "json", // used by jQuery
DATA_TYPE_EXT : "ajax", // used by ExtJs
DATA_TYPE_TXT : "text", // used for tests
SaveWorkflow : function(code)
{
jQuery.ajax({
url: WFD.Proxy.SERVICE_URL + "task=savemodel",
data: { code : code },
dataType : WFD.Proxy.DATA_TYPE,
type: 'POST',
success : function(data) {
WFD.Proxy.OnSaveWorkflowCallback(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Errore di comunicazione: " + errorThrown);
}
});
}
,
WFD.Proxy.OnSaveWorkflowCallback = function(data)
{
/*
data.response
data.message
data.model_new_id
data.idsNodes[i].original_id
data.idsNodes[i].new_id
*/
}
};
I have written the code that converts an xml file to JSON format. The JSON string that i get from the code I've written until now, should be passed as the code parameter of SaveWorkflow : function(code) .
I'm not really sure what do I have to do at this point.
I did some searches and saw that jQuery.ajax() calls where manipulated using Java Servlets ...
Any idea how to resolve this please?
Thanks in advance
What you've written is client side code (i.e. executes in your browser). The part that's missing is the server side. Your "ajax call" is making an asynchronous connection to a web server, using this URL:
/delegate/WFD/WFService?task=savemodel&code=xxxx
xxxx is the value of the code variable. Your javascript is expecting a text string as response from this URL.
You don't need a servlet per se to handle this. Any web server that accepts the ajax URL and returns the required data will do (e.g. PHP...)
If you need a servlet and you don't know how to build one, I think you have a lot of reading to do.
I suggest:
https://www.google.be/search?q=my+first+servlet