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, ", "));
}
}
Related
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;
}
}
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);
}
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.
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
I have JSON object as follows:
member = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
In Java I want to parse the above json object and store the values in an arraylist.
I am seeking some code through which I can achieve this.
I'm assuming you want to store the interestKeys in a list.
Using the org.json library:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}
public class JsonParsing {
public static Properties properties = null;
public static JSONObject jsonObject = null;
static {
properties = new Properties();
}
public static void main(String[] args) {
try {
JSONParser jsonParser = new JSONParser();
File file = new File("src/main/java/read.json");
Object object = jsonParser.parse(new FileReader(file));
jsonObject = (JSONObject) object;
parseJson(jsonObject);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void getArray(Object object2) throws ParseException {
JSONArray jsonArr = (JSONArray) object2;
for (int k = 0; k < jsonArr.size(); k++) {
if (jsonArr.get(k) instanceof JSONObject) {
parseJson((JSONObject) jsonArr.get(k));
} else {
System.out.println(jsonArr.get(k));
}
}
}
public static void parseJson(JSONObject jsonObject) throws ParseException {
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
if (jsonObject.get(obj) instanceof JSONArray) {
System.out.println(obj.toString());
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
parseJson((JSONObject) jsonObject.get(obj));
} else {
System.out.println(obj.toString() + "\t"
+ jsonObject.get(obj));
}
}
}
}}
Thank you so much to #Code in another answer. I can read any JSON file thanks to your code. Now, I'm trying to organize all the elements by levels, for could use them!
I was working with Android reading a JSON from an URL and the only I had to change was the lines
Set<Object> set = jsonObject.keySet();
Iterator<Object> iterator = set.iterator();
for
Iterator<?> iterator = jsonObject.keys();
I share my implementation, to help someone:
public void parseJson(JSONObject jsonObject) throws ParseException, JSONException {
Iterator<?> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String obj = iterator.next().toString();
if (jsonObject.get(obj) instanceof JSONArray) {
//Toast.makeText(MainActivity.this, "Objeto: JSONArray", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString());
TextView txtView = new TextView(this);
txtView.setText(obj.toString());
layoutIzq.addView(txtView);
getArray(jsonObject.get(obj));
} else {
if (jsonObject.get(obj) instanceof JSONObject) {
//Toast.makeText(MainActivity.this, "Objeto: JSONObject", Toast.LENGTH_SHORT).show();
parseJson((JSONObject) jsonObject.get(obj));
} else {
//Toast.makeText(MainActivity.this, "Objeto: Value", Toast.LENGTH_SHORT).show();
//System.out.println(obj.toString() + "\t"+ jsonObject.get(obj));
TextView txtView = new TextView(this);
txtView.setText(obj.toString() + "\t"+ jsonObject.get(obj));
layoutIzq.addView(txtView);
}
}
}
}
1.) Create an arraylist of appropriate type, in this case i.e String
2.) Create a JSONObject while passing your string to JSONObject constructor as input
As JSONObject notation is represented by braces i.e {}
Where as JSONArray notation is represented by square brackets i.e []
3.) Retrieve JSONArray from JSONObject (created at 2nd step) using "interests" as index.
4.) Traverse JASONArray using loops upto the length of array provided by length() function
5.) Retrieve your JSONObjects from JSONArray using getJSONObject(index) function
6.) Fetch the data from JSONObject using index '"interestKey"'.
Note : JSON parsing uses the escape sequence for special nested characters if the json response (usually from other JSON response APIs) contains quotes (") like this
`"{"key":"value"}"`
should be like this
`"{\"key\":\"value\"}"`
so you can use JSONParser to achieve escaped sequence format for safety as
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(inputString);
Code :
JSONParser parser = new JSONParser();
String response = "{interests : [{interestKey:Dogs}, {interestKey:Cats}]}";
JSONObject jsonObj = (JSONObject) parser.parse(response);
or
JSONObject jsonObj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> interestList = new ArrayList<String>();
JSONArray jsonArray = jsonObj.getJSONArray("interests");
for(int i = 0 ; i < jsonArray.length() ; i++){
interestList.add(jsonArray.getJSONObject(i).optString("interestKey"));
}
Note : Sometime you may see some exceptions when the values are not available in appropriate type or is there is no mapping key so in those cases when you are not sure about the presence of value so use optString, optInt, optBoolean etc which will simply return the default value if it is not present and even try to convert value to int if it is of string type and vice-versa so Simply No null or NumberFormat exceptions at all in case of missing key or value
From docs
Get an optional string associated with a key. It returns the
defaultValue if there is no such key.
public String optString(String key, String defaultValue) {
String missingKeyValue = json_data.optString("status","N/A");
// note there is no such key as "status" in response
// will return "N/A" if no key found
or To get empty string i.e "" if no key found then simply use
String missingKeyValue = json_data.optString("status");
// will return "" if no key found where "" is an empty string
Further reference to study
How to convert String to JSONObject in Java
Convert one array list item into multiple Items
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
Performance
Ease of use (code is simple to write and legible) - that goes with features.
For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
public class MyObj {
private List<Interest> interests;
static final class Interest {
private String interestKey;
}
private static final ObjectMapper MAPPER = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue("{\"interests\": [{\"interestKey\": \"Dogs\"}, {\"interestKey\": \"Cats\" }]}", MyObj.class);
}
}
Let me know if you have any questions.
I'm wondering, can I have text like this:
ps:mandatory' child of Input command functions
Properties
ps:Source:
f47437
ps:Created:
2010-09-03T11:38:02.629Z
ps:ChangedBy:
F47437
ps:Changed:
2011-09-07T07:51:10.864Z
In JSON format. The problem is there ..that the file includes tens of thousands of that text type and they're like tree family. And my point is to convert it to JSON saving the same tree logic. I just wanted to ask for my own knowledge.
Do you mean like this?
{
"ps:mandatory": "Properties",
"ps:Source:": "f47437",
"ps:Created:": "2010-09-03T11:38:02.629Z",
"ps:ChangedBy:": "F47437",
"ps:Changed:": "2011-09-07T07:51:10.864Z"
}
It's important to remember that JSON is unordered so you will most likely lose the order of the tags when storing it in JSON. If order is important, consider another file format.
The following code will turn your data above into JSON. Compiles and works:
import org.json.*;
public class CreateMyJSON
{
public static void main(String[] args)
{
String testData = "ps:mandatory\nProperties\n\nps:Source:\n f47437\n\nps:Created:\n 2010-09-03T11:38:02.629Z\n\nps:ChangedBy:\n F47437\n\nps:Changed:\n 2011-09-07T07:51:10.864Z\n\n";
CreateMyJSON cmj = new CreateMyJSON();
System.out.println(cmj.getJSONFromString(testData));
}
public String getJSONFromString(String theData)
{
JSONObject jso = new JSONObject();
//no error checking, but replacing double returns
//to make this simpler
String massagedData = theData.replaceAll("\n\n", "\n");
String[] splits = massagedData.split("\n");
for(int i = 0; i < splits.length; i++)
{
jso.put(splits[i].trim(), splits[++i].trim());
}
return jso.toString();
}
}