Replace json to java string [duplicate] - java

This question already has an answer here:
json object convert to string java
(1 answer)
Closed 2 years ago.
Hi Guys I'm new to programming.
In my java code i have string like this.
String json ="{"name":"yashav"}";
Please help me out to print the values using pre-build java functions.
Expected output should be like below
name=yashav

First of all its not JSON.
If you want to work for actual JSON. There are many libraries which help you to transfer string to object.
GSON is one of those libraries. Use this to covert object then you can use keys to get values. Or you can iterate whole HashMap as per your requirements.
https://github.com/google/gson

{name:yashav} this is not a valid JSON format.
If you have {"name": "yashav"} you can use Jackson to parse JSON to java object.
class Person {
String name;
...
}
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue("{\"name\" : \"mkyong\"}", Person.class);

Forst of all, given String is NOT a json. It should be "{\"name\":\"yashav\"}". If you have a correct json string, you can use JacksonUtils.
Define a model:
class Url {
private String name;
public String getName() {
return name;
}
}
And parse the json string:
String json = "{\"name\":\"yashav\"}";
Url url = JsonUtils.readValue(json, Url.class);
System.out.format("name = %s", url.getName());
Another way is to use Regular Expression:
public static void main(String... args) {
String url = "{name:yashav}";
Pattern pattern = Pattern.compile("\\{(?<key>[^:]+):(?<value>[^\\}]+)\\}");
Matcher matcher = pattern.matcher(url);
if (matcher.matches())
System.out.format("%s = %s\n", matcher.group("key"), matcher.group("value"));
}
And finally, you can use plain old String operations:
public static void main(String... args) {
String url = "{name:yashav}";
int colon = url.indexOf(':');
String key = url.substring(1, colon);
String value = url.substring(colon + 1, url.length() - 1);
System.out.format("%s = %s\n", key, value);
}

Related

Retrieving each key-value from String array object [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 1 year ago.
I have a string in below format and would want to access certain elements from it such as host/username.
{
"username":"admin",
"password":"admin1234",
"engine":"mysql",
"host":"toolsdata.us-east-1.rds.amazonaws.com",
"port":3306,
"dbname":"tools_data",
"dbInstanceIdentifier":"toolsdata
}
I tried using List<String> or String[] to retrieve values, but unable to do so.
Is there another way I can get the each element from above string?
You can use org.json.JSONObject (https://mvnrepository.com/artifact/org.json/json) class in order to access key-value features.
To create JSONObject just pass JSON value as string to its constructor:
String jsonAsString = "Your JSON as string...";
JSONObject json = new JSONObject(jsonAsString);
And now you can easily access value by given key:
json.getString("username");
json.getInt("port");
You can learn more about different JSON parsing approaches in this tutorial: How to Parse JSON in Java
A String containing JSON is just a string. It will not magically be parsed into anything else. Not split into lines, not interpreted as Json, nothing. And how would it, Java doesn't know about its contents or what meaning it has to you.
So, to be able to process the JSON, you have to write code that tokenizes and parses the JSON into Objects that provide the necessary functions to access its keys and values.
There is multiple libraries that prvide those capabilities. Amongst the most capable and well known ones are Jackson and GSON, but they might be an overkill for a task as simple as yours. A simpler library like JSONObject might suffice.
The main difference is: JSON serializeation / deserialization libraries like Jackson or GSON parse known Json into user-defined objects. If the fields in JSON and in your Java object don't match, it won't work. But IF they do, you have type-safe access to all the keys and can use your Object like any regular Java object.
Libraries like JSONObject work differnetly: They don't need to know anything about your JSON Objects, they parse it into Wrapper objects that you can then query for data. They can work with any valid JSON input, but if you make assumptions about which keys are present and which type they have, and those assumptions do not hold true, you can errors when accessing them. So, no type-safety here.
Code below does NOT account for potential exceptions thrown by any of the libraries and noes not include any null-checks either.
Jackson:
class Settings {
String username;
String password;
String engine;
String host;
Integer port;
String dbname;
String dbInstanceIdentifier;
public static Settings fromJson (String jsonData) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(jsonData, Settings.class);
}
}
GSON
class Settings {
String username;
String password;
String engine;
String host;
Integer port;
String dbname;
String dbInstanceIdentifier;
public static Settings fromJson (String jsonData) {
Gson gson = new Gson();
return gson.fromJson(jsonData, Settings.class);
}
}
JSONObject:
class Settings {
String username;
String password;
String engine;
String host;
Integer port;
String dbname;
String dbInstanceIdentifier;
public static Settings fromJson (String jsonData) {
JSONObject json = new JSONObject(jsonData);
Settings newSettings = new Settings();
newSettings.username = json.getString("username");
newSettings.password = json.getString("password");
newSettings.engine = json.getString("engine");
newSettings.host = json.getString("host");
newSettings.port = json.getInt("port");
newSettings.dbname = json.getString("dbname");
newSettings.dbInstanceIdentifier = json.getString("dbInstanceIdentifier");
return newSettings;
}
}

How can I convert each integer/double value to String from JSON data containing nested objects and arrays?

I want to convert each integer/double value to String present in json request before storing in MongoDB database.
There can be multiple fields like amountValue in the json. I am looking for a generic way which can parse json with any number of such attributes value to string. My request will have around 200 fields.
ex: "amountValue": 200.00, to "amountValue": "200.00",
{
"templateName": "My DC Template 14",
"templateDetails": {
"beneficiaryName": "Snow2",
"dcOpenAmount": {
"amountValue": 200.00,
}
}
}
My mongoDB Document is of the form
#Document
public class TemplateDetails {
#Id
private long templateId;
private String templateName;
private Object templateDetail;
}
Because we are storing document in mongodb as an object(Which can accept any type of json request) we dont have field level control on it.
In my controller, converting the request object to json.
This is how I tried. But its not meeting my expectation. It is still keeping the amount value to its original double form.:
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(templateRequestVO);
System.out.println("ResultingJSONstring = " + json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Output :
ResultingJSONstring = {"id":null,"userId":"FU.ZONKO","txnType":"LCI","accessIndicator":"Public","templateId":null,"templateName":"My DC Template 14","tags":null,"templateDetails":{"applicantDetail":{"applicantName":"Tom","applicantAddress":{"addressLine1":"Infosys, Phase 2","city":"PUNE","state":"MAHARASHTRA","country":"INDIA","zip":"40039"},"accountId":"Account1234","customerId":"JPMORGAN"},"beneficiaryName":"Snow2","dcOpenAmount":{"amountValue":200.0,"currency":"USD"}}}
Is there any way to accomplish the result ? Or anything which can help to store documents in mongodb with attribute type as String ?
You can use Json manipulation avaliable in "org.json.JSONObject" to convert Double value to Stirng .
If your Json structure won't change and will remain as said above , you can do the following.
import org.json.JSONObject;
public static void main(String args[]) {
String j = "{ \"templateName\": \"My DC Template 14\", \"templateDetails\": { \"beneficiaryName\": \"Snow2\", \"dcOpenAmount\": { \"amountValue\": 200.00 } } }";
JSONObject jo = new JSONObject(j);
jo.getJSONObject("templateDetails")
.getJSONObject("dcOpenAmount")
.put("amountValue", String.valueOf(jo.getJSONObject("templateDetails").getJSONObject("dcOpenAmount").getDouble("amountValue")));
System.out.println(jo.toString());
}
Following will be the output
{"templateDetails":{"dcOpenAmount":{"amountValue":"200.0"},"beneficiaryName":"Snow2"},"templateName":"My DC Template 14"}
I don't know for mongodb but for a json string you can replace them with a regex and the function replace like this :
public class Test {
public static void main(String[] args) {
String json = "{\"id\":null,\"userId\":\"FU.ZONKO\",\"txnType\":\"LCI\",\"accessIndicator\":\"Public\",\"templateId\":null,\"templateName\":\"My DC Template 14\",\"tags\":null,\"templateDetails\":{\"applicantDetail\":{\"applicantName\":\"Tom\",\"applicantAddress\":{\"addressLine1\":\"Infosys, Phase 2\",\"city\":\"PUNE\",\"state\":\"MAHARASHTRA\",\"country\":\"INDIA\",\"zip\":\"40039\"},\"accountId\":\"Account1234\",\"customerId\":\"JPMORGAN\"},\"beneficiaryName\":\"Snow2\",\"dcOpenAmount\":{\"amountValue\":200.0,\"currency\":\"USD\"}}}";
System.out.println(replaceNumberByStrings(json));
}
public static String replaceNumberByStrings(String str){
return str.replaceAll("(?<=:)\\d+(\\.\\d+)?(?=(,|}))","\"$0\"");
}
}
It will look for all fields with a numeric value in the json string and add quotes to the value. This way they will be interpreted as strings when the json willl be parsed.
It will not work if the value is in an array though, but in this case it should not be a problem.

Convert Integer to specific String format

I have an integer value, say int id whose value i get runtime by getter function.
I want to replace this value of id in place of "VALUE" from .json like as follows
{
"id":"VALUE",
"name": "Name updated",
"description": "description Updated",
"active": false
}
I found following way to replace it if id is String,
String str = "myJson.json";
str.replace("\"VALUE\"", "\"id\"");
How can i use int id in above function with this format "\"id\"" ?
Any other solution are welcome.
EDIT:
String str = "myJson.json";
is wrong way to get json content into String.
You can do it with simple regex replace, e.g.:
public static void main(String[] args) {
String value = "{\"id\":\"VALUE\",\"name\": \"Name updated\",\"description\": \"description Updated\",\"active\": false}";
int id = 5;
value = value.replaceAll("\"VALUE\"", String.valueOf(id));
System.out.println(value);
}
Using org.json library you can assign it to JSON Object and Use the put method:
JSONObject jsonObject= new JSONObject(YOUR_STRING);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
JSONObject id= jsonArray.getJSONObject(0).getJSONObject("id");
person.put("VALUE", id);
regex replace may create some issue by replace someother matching string .
I did in following way.
To replace content of Json file need to convert contents in to String. I did this with help of following function.
public static String loadJson(String jsonFileName) throws IOException {
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(jsonFileName);
return IOUtils.toString(stream);
}
Then declare a String variable,
String editedJson = loadJson(TEST_SET + "myJson.json");
editedJson.replace("VALUE", "" + id);

Converting a JSON string to custom objects in java [duplicate]

This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 6 years ago.
I'm trying to convert a the following string so that I can get the properties out of it. I'm trying to insert these in the DB by getting their properties and then making objects out of them
[{"ParkingSpaces;;;;":"Name;CarPlate;Description;ExpirationDate;Owner"},{"ParkingSpaces;;;;":"A5;T555;Parkingspace A5;;"},{"ParkingSpaces;;;;":"A6;T666;Parkingspace A6;;"},{"ParkingSpaces;;;;":"A7;T777;Parkingspace A7;;"},{"ParkingSpaces;;;;":""}]
I got this string from a CSV file.
Anyone who has an idea on how I can approach this?
Thanks in advance.
Your code is quite messy, but it's doable. You can either use simple JSON parsing method like in the example:
final String json = "[{\"ParkingSpaces;;;;\":\"Name;CarPlate;Description;ExpirationDate;Owner\","
{\"ParkingSpaces;;;;\":\"A5;T555;Parkingspace A5;;\"},{\"ParkingSpaces;;;;\":\"A6;T666;Parkingspace A6;;\"},{\"ParkingSpaces;;;;\":\"A7;T777;Parkingspace A7;;\"},{\"ParkingSpaces;;;;\":\"\"}]";
final org.json.JSONArray jSONArray = new JSONArray(json);
for (int i = 0; i < jSONArray.length(); i++) {
final org.json.JSONObject jSONObject = jSONArray.getJSONObject(i);
final String parkingSpaces = jSONObject.getString("ParkingSpaces;;;;");
final String spaces[] = parkingSpaces.split(";");
System.out.println(Arrays.toString(spaces));
}
}
or use some bindings like Jackson.
What you have there is JSON with some semicolon separated strings in it. I wouldn't call this a CSV format at all.
You could parse the JSON to Java objects with a JSON parser like Gson, but you'll still need to pick the "columns" out of the Java object since they are not properly defined in JSON.
Something like this should work, I recommend you add more error checking than I have though:
public class DBEntry {
#SerializedName("ParkingSpaces;;;;")
#Expose
private String ParkingSpaces;
public String getParkingSpaces() {
return ParkingSpaces;
}
public void setParkingSpaces(String ParkingSpaces) {
this.ParkingSpaces = ParkingSpaces;
}
}
public static void main(String[] args) {
String json = "[{\"ParkingSpaces;;;;\":\"Name;CarPlate;Description;ExpirationDate;Owner\"},{\"ParkingSpaces;;;;\":\"A5;T555;Parkingspace A5;;\"},{\"ParkingSpaces;;;;\":\"A6;T666;Parkingspace A6;;\"},{\"ParkingSpaces;;;;\":\"A7;T777;Parkingspace A7;;\"},{\"ParkingSpaces;;;;\":\"\"}]";
// Convert JSON to java objects using the popular Gson library
Gson gson = new Gson();
Type collectionType = new TypeToken<ArrayList<DBEntry>>(){}.getType();
List<DBEntry> results = gson.fromJson(json, collectionType);
boolean header = true;
for (DBEntry result : results) {
// Ignore the header and empty rows
if (header || result.getParkingSpaces().isEmpty()) { header = false; continue; }
// Grab the columns from the parking spaces string
String[] columns = result.getParkingSpaces().split(";");
// TODO: Store this record in your database
System.out.println("New entry: " + StringUtils.join(columns, ", "));
}
}

Reading JSON String using JSON/Gson

I have the JSON String of the below format which I get as a http request in Java. I need to get the name and values of the below JSON string, but I am not able to get the correct solution.
Can any one tell me how to parse this? Also, let me know if we will be able to format this string because there is no property names from the 3 element.
The string format is
{
'appname':'application',
'Version':'0.1.0',
'UUID':'300V',
'WWXY':'310W',
'ABCD':'270B',
'YUDE':'280T'
}
edit#1 formatted the question.
In JavaScript, you can do something like
var v = eval("("+data_from_server+")");
var aName = v.appname;
For example this script will alert appname.
<script>
var serverdata = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
var v = eval("("+serverdata+")");
alert(v.appname);
</script>
Based on your comment on this answer, here is a way to parse in Java
In Java, you may want to leverage GSon. See here.
You need to define a Java class that maps the JSON object one-to-one. Then ask GSon to create a Java object using the JSON String. Here is the example.
Your Java class that maps JSON should look like this
public class MyData{
public String appname;
public String Version;
public String UUID;
public String WWXY;
public String ABCD;
public String YUDE;
public MyData(){}
}
And you parse in Java like this.
String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
Gson gson = new Gson();
MyData obj = gson.fromJson(jsons, MyData.class);
System.out.println("ada "+ obj.appname);
With which language do you want to do that ?
Here is the solution for PHP :
$data = json_decode('the json');

Categories

Resources