My input is something like:
List.of("customer.name", "customer.phone", "shop.address", "nr")
And I have to get the JSON tree hierarchy like:
{
customer: {
name: "",
phone: "",
},
shop: {
address: ""
},
nr: ""
}
I am using Java and 'org.json', 'com.jayway.jsonpath' JSON dependencies.
Do you have any ideas, please?
Thank you!
you could do something like this:
import org.json.JSONObject;
List<String> input = List.of("customer.name", "customer.phone", "shop.address", "nr");
JSONObject root = new JSONObject();
for (String s : input) {
// Split the string by the '.' character to get the keys
String[] keys = s.split("\\.");
JSONObject obj = root;
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
if (i < keys.length - 1) {
if (!obj.has(key)) {
obj.put(key, new JSONObject());
}
obj = obj.getJSONObject(key);
} else {
obj.put(key, "");
}
}
}
Related
How to update few fields in JSON file and again read the JSON with updated values in selenium using Java.
Below is my JSON :
I want to update
{
"DemoFileJson": [
{
"name": "demoPan",
"Type": "patientcare",
"indication": "fever",
"disease": {
"code": "282292002",
"label": "Uncertain diagnosis"
},
"identified": false,
"specimens": [
{
"name": "primarySpecimen",
"type": {
"code": "442524009",
"label": "a.m. specimen"
},
"studyIdentifier": "Stud1",
"studySubjectIdentifier": "Part1",
"accessionNumber": "TSO500-MJ678",
"dateAccessioned": "2019-03-29T20:00:00Z",
"datecollected": "2019-03-29T20:00:00Z",
"dateReceived": "2019-03-29T20:00:00Z"
}
]
}
]
}
search & update value json file, with java class
example json file
[{"trx_id":"123"},{"trx_id":"123","datetime_expired":"20221102"}]
public class cariJSON {
public static void main(String[] args)throws Exception {
JSONArray dd = updateJson("datetime_expired", "20331001");
try (FileWriter file = new FileWriter("C://file.json")) { //store data
file.append(dd.toString());
file.flush();
}
System.out.println(dd);
}
public static JSONArray updateJson(String keyString, String newValue) throws Exception {
String jsons = readFileAsString("C://file.json");
JSONArray jsonArray = new JSONArray(jsons);
for (int j = 0; j < jsonArray.length(); j++)
{
JSONObject obj = new JSONObject(jsonArray.get(j).toString());
// get the keys of json object
if (obj.get("trx_id").equals("123"))
{
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if the key is a string, then update the value
if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
if ((key.equals(keyString))) {
obj.put(key, newValue);
jsonArray.remove(j);
return jsonArray.put(obj);
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
updateJson(keyString, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
updateJson(keyString, newValue);
}
}
}
}
System.out.println("Output array : " + jsonArray);
return jsonArray;
}
return null;
}
}
#Path("/getVersion")
#POST
#Produces(MediaType.APPLICATION_JSON)
public String getVersion(String getVersionJson) {
String version = "", patches = "", connectionStatus = "", output1 = "", output2 = "";
try {
JSONObject inputJson = new JSONObject(getVersionJson);
String ip = inputJson.getString("ipaddress").trim();
String userName = inputJson.getString("username").trim();
String passWord = inputJson.getString("password").trim();
connectionStatus = getSSHConnection(ip, userName, passWord);
if (connectionStatus.equals("Connected")) {
//Version Check
expect.send("bwshowver" + "\n");
if (expect.expect("$") > -1) {
String contt = "";
contt = (expect.before);
if (contt != null && contt != "") {
contt = contt.replaceAll("\n+", "\n");
contt = contt.replaceAll(" +", " ");
String splitter[] = contt.split("\n");
for (int i = 0; i < splitter.length; i++) {
//
if (splitter[i].contains("Patches")) {
patches = splitter[i];
}
//version
if (splitter[i].contains("version")) {
version = splitter[i];
}
// output1=version.toString();
// output2=patches.toString();
// output3=output1+output2;
//
output1 = contt;
}
}
} else {
output1 = "Error in version check";
System.out.println("Error in version check");
}
} else {
output1 = connectionStatus;
System.out.println(connectionStatus);
}
} catch (Exception e) {
output1 = "Error";
// logger.error("Exception in getVersion Function-ServService Class: " + e.getMessage());
} finally {
stopSSH();
}
return output3;
}
//The string which is being passed from getVersion comprises of
[{"ipaddress":"10.253.140.116","password":"c0mcast!","username":"bwadmin"},{"ipaddress":"10.253.140.117","password":"bwadmin!","username":"bwadmin"}]
//My requirement is to access the value of ipaddress and password and username and store items in an array and send them to ConnectionStatus.
JSONArray jsonArr = new JSONArray(getVersionJson);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
//Now you can fetch values from each JSON Object
}
JSONObject class represents just one JSON. This is generally inside braces { and }.
If the expected input getVersionJson is just one JSON object, your code works.
However, you are getting an array of JSON objects in the input string getVersionJson, so you need to use JSONArray class to handle an array of JSON Objects.
This is generally [ { }, { }, { }, ... ]
JSONArray extends List, so it can be iterated to read each JSONObject value.
Here is documentation for reference: Interface JsonArray.
I have a json string string from which I want to get the values. It is in key pair form so I want the values for each key.
I tried to get the values but I am not getting it.
Json String is like :
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
I want to get values of "Name", "Address", "Company" etc.
I tried to get like this:
JSONArray array;
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
array = object.getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(i);
edt_FirstName.setText(object.getString("Name"));
}
} catch (JSONException e) {
}
Can anyone help me out please? Thank you..
EDIT:
I tried to check values like this:
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(0);
String type = subObject1.getString("type");
String value = subObject1.getString("value");
if (type.equals("Name")) {
edt_FirstName.setText(value);
}
if(type.equals("Address"))
{
edt_address.setText(value);
}
if(type.equals("Company"))
{
edt_company.setText(value);
}
if(type.equals("Mobile"))
{
edt_Mobile.setText(value);
}
}
I want to get all the values from field array and set to the text view, but I am getting only the Name value and not the others.
Also I could get one field as twice like Mobile I can get twice, so I want to combine both the Mobile values and show it.
So your json object is as follow:
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
You first need to get "document" as JSONObject and then get "businessCard" as JSONObject and then you can get "field" as JSONArray:
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
JSONArray array = object.getJSONObject("document").getJSONObject("businessCard").getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject = array.getJSONObject(i);
String type = subObject.getString("type");
String value = subObject.getString("value");
if (type.equals("Name")) {
String prevValue = edt_FirstName.getText();
edt_FirstName.setText((TextUtils.isEmpty(prevValue) ? "" : prevValue + ",") + value);
}
}
} catch (JSONException e) { }
}
Try this code, Hope it will help you.
try
{
JSONObject jsonObject = new JSONObject();
JSONObject documentObject = jsonObject.getJSONObject("document");
JSONObject businessCardObject = documentObject.getJSONObject("businessCard");
String imgRotation = businessCardObject.getString("imageRotation");
JSONArray array = businessCardObject.getJSONArray("field");
for (int i = 0; i < array.length() ; i++)
{
JSONObject arrObj = array.getJSONObject(i);
String type = arrObj.getString("type");
String value = arrObj.getString("value");
Log.e(TAG, "type=="+type);
Log.e(TAG, "value=="+value);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
here is code
private void convertJsonToDto(String jsonNewString) {
JSONObject jsonObj = new JSONObject(jsonNewString);
String RecordLocator = (String) jsonObj.get("obj");
String FirstName = (String) jsonObj.getJSONObject("Customer").get("FirstName");
JSONArray array = new JSONObject(jsonNewString).getJSONArray("Array");
JSONObject jsonObject = array.getJSONObject(0);
String str = jsonObject.getString("object");
}
Given a sample JSON:
{
"hello" : "wolrd",
"arrayField" : ["one", "two", "three"],
"mapField" : {
"name" : "john",
"lastName" : "doe"
}
}
Is there a framework in Java to help me get the JSON path structure from the JSON tree? Something similar to this:
$.hello
$.arrayField[0]
$.arrayField[1]
$.arrayField[2]
$.mapField.name
$.mapField.lastName
EDIT:
I've already coded a first approach using fasterxml's Jackson. But I'd like to know if there's something more robust / flexible.
final JsonNode rootNode = mapper.readValue(jon, JsonNode.class);
printFieldKeys(rootNode, "$");
private static void printFieldKeys(JsonNode rootNode, String parent) {
final Iterator<Entry<String, JsonNode>> fieldIt = rootNode.fields();
while (fieldIt.hasNext()) {
final Entry<String, JsonNode> next = fieldIt.next();
final JsonNode value = next.getValue();
final String path = parent + "." + next.getKey();
if (value.isValueNode()) {
System.out.println(path + " = " + value.asText());
} else {
System.out.println(path);
}
if (value.isArray()) {
for (int i = 0; i < value.size(); i++) {
printFieldKeys(value.get(i), path + "[" + i + "]");
}
} else {
printFieldKeys(value, path);
}
}
}
Take a look at this library: https://github.com/jayway/JsonPath
I believe it does exactly what you want. :)
I have a JSON response which look something like this( its different from user to user)
{
"success": true, "data":
[
{
"mandatory_tag": "My Company",
"id": "topic_1408946825893148"
},
{
"mandatory_tag": "Partners",
"id": "topic_1408946942491149",
},
{
"mandatory_tag": "Industry",
"id": "topic_1408946996510150",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210454810358",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947133657152"
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947071457151",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210621754362",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210704390363",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210794791364"
}
]
}
I am parsing it and trying to store in HashMap, but the key value is duplicating. Can anyone suggest me how can i store all id with same mandatory_tag in one array?
I am new to this so please consider..thanks
try
{
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
} else
{
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}
And well i got stuck at this now..any good logic please..
A hashmap allows you to store key-value items. I would suggest the HashMap be of type <String,List<String>> so allowing you to store items with the same mandatory_tag in the same list under 1 key.
For example
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
if (myMap.containsKey(mandatory_tag)) {
List<String> values = myMap.get(mandatory_tag);
if (values!=null) {
values.add(id)
} else {
values = new List<String>();
values.add(id);
}
}
Update
As I wrote in my comment below, the except you added has an error
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
What you are doing here is, if the map already contains the key you are replacing the value associated with the key with a new list which contains only 1 value. What you need to do is update the list of already existing values. Check the code below and make sure you understand the problem. These are fundamentals of programming and you need to understand the logic of what you're doing to advance.
//Somewhere you have declared your HashMap
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
//then we continue with your excerpt
try {
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++) {
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.containsKey(mandatory_tag)) {
List<String> arrayID = myMap.get(mandatory_tag);
arrayID.add(id);
} else {
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}
Create a POJO called TagValues(or whatver name you would like) with variables mandatory_tag,id and then and create an ArrayList<TagValues> in which you can store all the objects.
Thanks for your response, but with help of you guys, i got the solution
`HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.isEmpty())
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
}`
In those cases, I'd like to use a custom HashMap:
public MMap getData() {
MMap result = new MMap();
JSONArray array = getJSONArrayFromTotalJSON();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String mtag = obj.getString(MANDATORY_TAG);
String id = obj.getString(ID);
result.put(mtag, id);
}
return result;
}
public class MMap extends HashMap<String, List<String>> {
public void put(String key, String value) {
if (!this.containsKey(key))
this.put(key, new ArrayList<String>());
this.get(key).add(value);
}
}