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

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;
}
}

Related

How to convert json formated java string to json object in controller

All examples of converting string to json are of javascript. mine is java class. So, i have a simple java string but formated in json. now i have recieved that from jquery post. now i have to convert that string into json object so that i can access the specific fields.
controller class
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public void storeData(#RequestParam(value = "temp_str", required = false) String j_str, HttpServletRequest request) {
// do the conversion and extraction of data from "j_str"
}
j_str variable is recieveing this string
{"temp_data":[{"temp_email":"roykumarsuraj#gmail.com","temp_pwd":"abc123"}]}
http://www.javacreed.com/simple-gson-example/
Gson gson = new GsonBuilder().create();
Person p = gson.fromJson("your json string", Person.class);
System.out.println(p);
you can use that libary to manage json objectos its very cool
the Person.class is a java bean must have all properties you have in your string
If your Json string is extremely simple, you can just use:
JSONObject jobj=new JSONObject(j_str);
Now you can access the JSON elements by:
JSONArray jarr=jobj.getJSONArray('temp_data');
JSONObject jarr1=jarr.get(0); // will contain {"temp_email":"roykumarsuraj#gmail.com","temp_pwd":"abc123"}
Now you can further access jarr1 similar to jobj.

Java Parse String

I have a String in a following format:
{"id":"1263e246711d665a1fc48f09","facebook_username":"","google_username":"814234576543213456788"}
but sometimes this string looks like:
{"id":"1263e246711d665a1fc48f09","facebook_username":"109774662140688764736","google_username":""}
How can I extract those values if I do not know the index of substrings as they will change for different cases?
That looks like json format, you should give a look to the Gson library by google that will parse that string automatically.
Your class should look like this
public class Data
{
private String id;
private String facebook_username;
private String google_username;
// getters / setters...
}
And then you can simply create a function that create the object from the json string:
Data getDataFromJson(String json){
return (Data) new Gson().fromJson(json, Data.class);
}
That String is formated in JSON (JavaScript Object Notation). Is a common language used to transfer data.
You can parse it using Google's library Gson, just add it to your class path .
Gson gson = new Gson();
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class); //The object you want to convert to.
https://github.com/google/gson
Check this out on how to convert to Java Object
Parsing as JSON notwithstanding, here's a pure string-based solution:
String id = str.replaceAll(".*\"id\":\"(.*?)\".*", "$1");
And similar for the other two, swapping id for the other field names.

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, ", "));
}
}

How to create a new json string by changing one particular field in it?

I need to blur the user id present in my original json string with another user id. After that I will construct a new json string with everything same but the only difference will be the user id is different.
As an example, if my original json string is like this -
{
"user_id":{"long":1234},
"client_id":{"int":0},
"affinity":[
{
"try":{"long":55793},
"scoring":{"float":0.19}
},
{
"try":{"long":1763},
"scoring":{"float":0.0114}
}
]
}
Then my new json string will be - The only difference is I have a new user id in it and apart from that everything is same.
{
"user_id":{"long":98765},
"client_id":{"int":0},
"affinity": [
{
"try":{"long":55793},
"scoring":{"float":0.19}
},
{
"try":{"long":1763},
"scoring":{"float":0.0114}
}
]
}
The only problem I have is, I won't have json string in the above format only so I cannot use POJO to serialize my json string since my json string will have different formats but user_id field will always be like that in all my json string and it will be long as well. The other fields might be different depending on the json string I have.
I am using Gson to do this. I have got the below method but not sure how can I construct a new json with newUserId in it and everything should be same?
private static String creatNewJson(String originalJsonResponse, long newUserId) {
JsonElement jelement = new JsonParser().parse(originalJsonResponse);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("user_id");
// not sure what I should do here to construct a new json with newUserId
}
Or Gson is not the right way to do this? Should I be usingg regular expressions for this?
How about input.replaceAll("(\"user_id\":\\{\"long\":)\\d+", "$1" + newID)?

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