I am having a converting that in to Json with following code
JSONObject jsonformatted = (JSONObject)JSONSerializer.toJSON(map);
FileWriter writer = new FileWriter("myfile.json");
It is working fine and out put is following
[ {"date":"July 4th", "event":"Independence Day"} ]
But I want the following format with a variable assign get value in Json
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
How can i add a variable to that
You can add a new data using put method in JSONObject
JSONObject jsonformatted = (JSONObject)JSONSerializer.toJSON(map);
jsonformatted .put("assign ", "some value")
Edit
OP wants to replace ':' with '='
Well you should not do it , because its the JSON standard.
Attributes and values are assigned using : and not by =
Check this link for more info
JSON wiki
Related
I am currently using JsonObject and JsonParser of com.google.gson api (using gson-2.8.5 version) to parse and read the value form input JSON.
I have JSON filed like , smaple "resultCode":"SUCCESS", when I try to read the same value from json it gives the result as ""SUCCESS"" .
Every value I am reading, getting with double "" not sure why ? You can refer below screen of my debugging screen.
I am new to Json and parser, is that default behavior ?
I am expecting "SUCCESS", "S", "00000000" not like ""SUCCESS"" or ""S""
or ""00000000""
same I have highlighted in the below image .
Please share any idea how we can get apbsolute vlaue of string without """" double quote string it causing my string comparison fail.
String response_result = "{\"response\": {\"head\": {\"function\": \"acquiring.order.create\",\"version\": \"2.0\",\"clientId\": \"201810300000\",\"reqMsgId\": \"56805892035\",\"respTime\": \"2019-09-13T13:18:08+08:00\"},\"body\": {\"resultInfo\": {\"resultCode\": \"SUCCESS\",\"resultCodeId\": \"00000000\",\"resultStatus\": S,\"resultMsg\": \"SUCCESS\"},\"acquirementId\": \"2018080834569894848930\",\"merchantTransId\": \"5683668701112717398\",\"checkoutUrl\": \"http://localhost:8081/crm/operator/operator-search-init.action\"}},\"signature\":\"d+TUYLvt1a491R1e6aO8i9VwXWzVhfNgnhD0Du74f4RgBQ==\"}";
HttpInvoker.Result result = i.new Result(200, response_result);
JsonObject jo = new JsonParser().parse(response_result).getAsJsonObject();
String resultCode = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().get("resultCode").toString();
String resultCodeId = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().get("resultCodeId").toString();
String resultStatus = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().get("resultStatus").toString();
String checkoutUrl = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("checkoutUrl").toString();
if ( RESULT_CODE_GCASH_SUCCESS.equals(resultCode)
&& RESULT_STATUS_SUCCESS.equals(resultStatus)
&& StringUtils.isNotEmpty(checkoutUrl)) {
log.error("Testing ".concat(resultCode).concat(resultStatus).concat(checkoutUrl));
}
log.error("Testing ".concat(resultCode).concat(resultStatus).concat(checkoutUrl));
}
This is my input JSON
{
"response":{
"head":{
"function":"acquiring.order.create",
"version":"2.0",
"clientId":"201810300000",
"reqMsgId":"56805892035",
"respTime":"2019-09-13T13:18:08+08:00"
},
"body":{
"resultInfo":{
"resultCode":"SUCCESS",
"resultCodeId":"00000000",
"resultStatus":"S",
"resultMsg":"SUCCESS"
},
"acquirementId":"2018080834569894848930",
"merchantTransId":"5683668701112717398",
"checkoutUrl":"http://localhost:8081/crm/operator/operator-search-init.action"
}
},
"signature":"d+TUYLvtI38YL2hresd98Ixu1BXccvvh1IQMiHuMXUEeW/N5exUsW491R1e6aO8i9VwXWzVhfNgnhD0Du74f4RgBQ=="
}
JsonParser parses your json into JsonElement structure. The behaviour that you see is a normal since you are using toString method of JsonElement. To achieve your goal just use JsonElement::getAsString method :
String resultCode = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().get("resultCode").getAsString();
which gives SUCCESS instead of "SUCCESS"
Note that JsonElement is an abstract class and classes, that extend this class, will override those helper getAs... methods. In your case JsonPrimitive::getAsString will be invoked.
Also you could create a POJO class for your json and use Gson::fromJson to parse json into object of your POJO class.
With the input from #Michalk:
I understand that easy way to read JSON data is using Gson::fromJson and creating POJO class for out json.
I have generated POJO Classes supplying my sample input JSON using this link
and Now I have POJO Classes called : CreateOrderJSONResponse
Gson::fromJson
Sample :
Gson gson = new Gson();
CreateOrderJSONResponse responseJson = gson.fromJson(inputJSON, CreateOrderJSONResponse.class);
Accessubg data :
String resultCodeText = responseJson.getResponse().getBody().getResultInfo().getResultCode();
String resultCodeId = responseJson.getResponse().getBody().getResultInfo().getResultCodeId();
String resultStatus = responseJson.getResponse().getBody().getResultInfo().getResultStatus();
String checkoutUrl = responseJson.getResponse().getBody().getCheckoutUrl();
Above Gson::fromJson example works smooth and it looks neat compare to direct accessing the filed with below sample code :
JsonObject jo = parser.parse(inputJSON).getAsJsonObject();
String resultCodeText = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().getAsJsonPrimitive("resultCode").getAsString();
String resultCodeId = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().getAsJsonPrimitive("resultCodeId").getAsString();
String resultStatus = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().get("resultInfo").getAsJsonObject().getAsJsonPrimitive("resultStatus").getAsString();
String checkoutUrl = jo.get("response").getAsJsonObject().get("body").getAsJsonObject().getAsJsonPrimitive("checkoutUrl").getAsString();
Note :
I have found this link of JSON or JAVA, SCALA, POJO generator tools as GitHub access you can access here
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 have a large file with many JSON objects similiar to the following. I need to parse everything to get the "bought_together" items as an array using the org.json library. I'm having trouble accessing anything nested in "related".
What is the required code to retrieve "bought_together" as a list?
{
"asin": "11158732",
"title": "Girls Ballet Tutu Zebra Hot Pink",
"price": 3.17,
"imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg",
"related":
{
"also_bought": ["L00JHONN1S", "B002BZX8Z6"],
"also_viewed": ["F002BZX8Z6", "B00JHONN1S", "B008F0SU0Y", "B00D23MC6W", "B00AFDOPDA"],
"bought_together": ["D202BZX8Z6"]
},
"salesRank": {"Toys & Games": 211836},
"brand": "Coxlures",
"categories": [["Sports & Outdoors", "Other Sports", "Dance"]]
}
Here is my attempt (Please note, this is within a MapReduce program so some lines may seem out of context.):
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONArray boughtTogether = new JSONArray(object.getJSONArray("bought_together"));
using the following code, I hope it's help you.
//this will be your json object that contains and convert your string to jsonobject
//if you have json object already skip this.
JSONObject yourJSON = new JSONObject(targetString);
//getting the "related" jsonObject
JSONObject related = yourJSON.getJSONObject("related");
//getting the "bought_together" as an jsonArray and do what you want with it.
//you can act with jsonarray like an array
JSONArray bought_together = related.getJSONArray("bought_together");
//now if you run blow code
System.out.print(bought_together.getString(0));
//output is : D202BZX8Z6
-------update according to update the question------
you should change your code like this:
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONObject related = object.getJSONObject("related");
JSONArray boughtTogether = related.getJSONArray("bought_together");
-------update-------
i think you need to this point (it's not technicality all of they difference)
every thing are in {} , they will be JSONObject and the relation
is key and value like :
{"name":"ali"}
this is a jsonobject and the value of key "name" is ali and we call it
like:
myJsonObject.getString("name");
every thing are in [] ,they will be JSONArray and the relation is
index and value like :
["ali"]
this is a JsonArray the value of index 0 is ali and we call it
like:
myJsonArray.getString(0);
so in your case:
your total object is a JSONObject
the value of "related" key is still a JSONObject
the value of "bought_together" key (which is inside the value of {jsonobject} "related" key) is a JSONArray
This question already has answers here:
JSONObject : Why JSONObject changing the order of attributes [duplicate]
(3 answers)
Closed 7 years ago.
When you add data in JSONObject it will store in it's own way.
Here is the Example of what i am trying to convey.
JSONObject obj = new JSONObject();
obj.put("metricname", "splunk-ui");
obj.put("timestamp", 1234567890);
obj.put("value",34);
System.out.println(obj);
Above code snippet will give below output.
{
"metricname": "splunk-ui",
"value": 34,
"timestamp": 1234567890
}
Here is the Problem :-
I add data in this sequence :- metricname , timestamp , value
This is the display sequence :- metricname , value , timestamp
So , how do i enforce my data adding sequence in JSONObject ??
FYI :- Doing this is mendatory as i will pass this JSON object to another API which can scan data in metricname , timestamp , value only.
HERE I AM POSTING CODE SNIPPET WHICH I USED FOR SOLVING THIS PROBLEM :-
I have used GSON library and this link to make this code work.
GSON Documention
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("metric", "mihirmonani");
jsonObject.addProperty("timestamp", 1346846400);
jsonObject.addProperty("value", 14);
JsonArray jArray = new JsonArray();
JsonObject jObject = new JsonObject();
jObject.addProperty("host", "splunk");
jObject.addProperty("host1", "splunk1");
jsonObject.add("tags",jObject);
System.out.println(jsonObject);
You can't with a JSONObject the only way to keep the order is using a JSONArray
[
{"name" : "metricname", "value" : "splunk-ui"},
{"name" : "value", "value" : 34},
{"name" : "timestamp", "value" : 1234567890}
]
Short answer: you can't. JSONObject uses a HashMap internally, which returns values depending on the order of the hash code.
You could use JSONWriter to write the values explicitly.
EDIT: To clarify, as Manu pointed out, you cannot retrieve the order after the values have been put in the JSONObject. My suggestion was to not put the values in the JSONObject to begin with, but use JSONWriter to write the values directly.
When I use Gson (JsonParser.parse) to decode the following:
{ "item": "Bread", "cost": {"currency": "\u0024", "amount": "3"}, "description": "This is bread\u2122. \u00A92015" }
The "currency" element is returned as a string of characters (and is not converted to a unicode character). Is there a setting or method in Gson that could help me?
If not, is there any way in Android to convert a string that contains one or more escaped character sequences (like "\u0024") to an output string with unicode characters (without writing my own and without using StringEscapeUtils from Apache)?
I'd like to avoid adding another library (for just one small feature).
Update
Looks like the server was double escaping the back slash in the unicode escape sequence. Thanks everyone for your help!
Is it only me or is it really more complicated than simply using TextView's setText() method? Anyhow, following is working just fine on my end with the given sample json (put the sample to assets and read it using loadJSONFromAsset()):
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(loadJSONFromAsset());
JsonObject obj = element.getAsJsonObject();
JsonObject cost = obj.getAsJsonObject("cost");
JsonPrimitive sign = cost.get("currency").getAsJsonPrimitive();
TextView tv = (TextView)findViewById(R.id.dollar_sign);
tv.setText(sign.getAsString());
Gson returns "$". Something is wrong in your set up.
String s = "{ \"item\": \"Bread\", \"cost\": {\"currency\": "
+ "\"\\u0024\", \"amount\": \"3\"}, \"description\": "
+ "\"This is bread\\u2122. \\u00A92015\" }\n";
JsonElement v = new JsonParser().parse(s);
assertEquals("$", v.getAsJsonObject().get("cost").getAsJsonObject()
.get("currency").getAsString());
You can parse it as a hex number
char c = (char)Integer.parseInt(str.substring(2), 16);