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.
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;
}
}
Are there any libraries to convert JSON in String/jackson/org.JSON.JSONOBJECT/etc... to a JSON schema?
So far, the only generator I found covert Java classes to JSON schemas. I'm about to write my own converted, but it'd be nice if I didn't have to re-invent the wheel.
looks like there isn't. I had to write my own generator.
Yes there is: https://github.com/java-json-tools/json-schema-validator. It ingests Jacson's JsonNode containing the schema definition and can validate JSON data against that schema.
You can use GSON library.
Convert Java object to JSON:
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON, and save into a file
gson.toJson(obj, new FileWriter("D:\\file.json"));
// 2. Java object to JSON, and assign to a String
String jsonInString = gson.toJson(obj);
Convert JSON to Java object:
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'foo'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);
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.
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)?
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');