I'm trying to use the StringUtils.removeAll method to delete parts of a string and keep the other parts:
String locations = [{"code":"b","name":"Beavercreek"},{"code":"bj","name":"Beavercreek Juvenile"},...]
Here is my regex
StringUtils.removeAll(result.get("locations").toString(),"\\{\"code\":,\"name\":^[a-zA-Z0-9_.-]*$\"\"\\}");
It doesn't remove anything, I can't get the regex correct?
It looks like the string your trying to parse is JSON so I would recommend using a JSON parser. For completeness however, I'll give you a solution using a regex as well.
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) throws Exception {
String locations = "[{\"code\":\"b\",\"name\":\"Beavercreek\"},{\"code\":\"bj\",\"name\":\"Beavercreek Juvenile\"}]";
// Parsing Using a JSON Parser (Recommended)
ObjectMapper jsonMapper = new ObjectMapper();
Model[] modelArray = jsonMapper.readValue(locations, Model[].class);
for(Model model : modelArray) {
System.out.println(model.toString());
}
// Parsing Using String.replaceAll with regex
locations = locations.replaceAll("\\{\"code\":", "");
locations = locations.replaceAll("\"name\":", "");
System.out.println(locations.replaceAll("\\}", ""));
}
static class Model {
private String code;
private String name;
public Model() { }
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return String.format("%s, %s", code, name);
}
}
}
Output:
// JSON Parsing
b, Beavercreek
bj, Beavercreek Juvenile
// REGEX Parsing
["b","Beavercreek","bj","Beavercreek Juvenile"]
Related
I want to parse JSON String into POJO class but I am getting error.
And
can we return two values from a method in java
String data
String PostcreatedMessage = "..."; // see JSON value below
{
"home_page":"/desk",
"message":"Logged In",
"full_name":"Shoaib Shaikh"
}
Main.class
LoginR loginR=new LoginR();
ObjectMapper mapper=new ObjectMapper();
loginR=mapper.readValue(PostcreatedMessage,LoginR.class);
System.out.println(loginR.getHomePage());
System.out.println(loginR.getMessage());
System.out.println(loginR.getFullName());
parsejacker.class
public class parsejacker
{
LoginR loginR=null;
String jsonurl;
public parsejacker(String jsonurl) {
super();
this.jsonurl = jsonurl;
}
public void ParseLogin() throws JsonParseException,JsonMappingException,IOException
{
System.out.println(jsonurl+"this parselogin");
ObjectMapper mapper=new ObjectMapper();
loginR=mapper.readValue(jsonurl,LoginR.class);
System.out.println(loginR.getHomePage());
System.out.println(loginR.getMessage());
System.out.println(loginR.getFullName());
}
}
LoginR.class
public class LoginR
{
private String homePage;
private String message;
private String fullName;
public String getHomePage(){
return homePage;
}
public void setHomePage(String input){
this.homePage = input;
}
public String getMessage(){
return message;
}
public void setMessage(String input){
this.message = input;
}
public String getFullName(){
return fullName;
}
public void setFullName(String input){
this.fullName = input;
}
}
I am Getting these errors.
(I think the error is in the PostcreatedMessage string.
How to overcome "home_page":"/desk"? --> this backslash error i.e delimiting or ignore this char)
Exception in thread "main" org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field "home_page" (Class org.greenshoaib.greenshaikh.login.model.LoginR), not marked as ignorable
at [Source: java.io.StringReader#4738a206; line: 1, column: 15]
(through reference chain: org.greenshoaib.greenshaikh.login.model.LoginR["home_page"])
at org.codehaus.jackson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:53)
at org.codehaus.jackson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:267)
at org.codehaus.jackson.map.deser.std.StdDeserializer.reportUnknownProperty(StdDeserializer.java:673)
at org.codehaus.jackson.map.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:659)
at org.codehaus.jackson.map.deser.BeanDeserializer.handleUnknownProperty(BeanDeserializer.java:1365)
at org.codehaus.jackson.map.deser.BeanDeserializer._handleUnknown(BeanDeserializer.java:725)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:703)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)
at org.greenshoaib.greenshaikh.rest.client.RestAPIClient.main(RestAPIClient.java:72 )
The problem is that your JSON contains a field "home_page" but in your pojo it's called homePage (same for "full_name"). Jackson doesn't know the two are equal so you need to help it, e.g. by adding #JsonProperty("home_page") to homePage, i.e. like this (and remember to do that same for fullName):
#JsonProperty("home_page")
private String homePage;
Try your method with the following json String :
PostcreatedMessage {
"homePage":"/desk",
"message":"Logged In",
"fullName":"Shoaib Shaikh"
}
Your problem here is that the ObjectMapper cannot recognize the properties of your LoginR class by name, e.g. homePage != home_page.
You can annotate those properties to match their expected JSON key.
Here's a minimal example:
public class LoginR {
#JsonProperty(value="home_page")
private String homePage;
#JsonProperty(value="full_name")
private String fullName;
// etc. the rest of your POJO
}
... somewhere else...
String json = "{\"home_page\":\"/desk\",\"message\":\"Logged In\",\"full_name\":\"Shoaib Shaikh\"}";
ObjectMapper mapper=new ObjectMapper();
LoginR loginR = mapper.readValue(json,LoginR.class);
System.out.println(loginR.getHomePage());
System.out.println(loginR.getMessage());
System.out.println(loginR.getFullName());
Output
/desk
Logged In
Shoaib Shaikh
Here is the JSON string return from API:
{"id":1,"bps_id":"C199","summary":{"as_of_date":"2017-06-20","bp_earned":0,"bp_balance":"199400","bp_redeemed":"600"},"bps_message":{"eng":"mobile testing message","chi":"mobile testing message chi"},"bps_image":"https:\/\/mydomain.com\/images\/eng\/promotion\/C199_MH.gif","error_message":{"eng":"","chi":""},"error_flags":""}
And I have created an object for this:
public class SummaryResponse {
String bps_id;
String bps_image;
String bps_message;
String as_of_date;
String bp_earned;
String bp_redeemed;
String bp_balance;
public String getBps_image() {
return bps_image;
}
public LangResponse getBps_message() {
return bps_message;
}
public String getAs_of_date() {
return as_of_date;
}
public String getBp_earned() {
return bp_earned;
}
public String getBp_redeemed() {
return bp_redeemed;
}
public String getBp_balance() {
return bp_balance;
}
}
It does not convert as expert, as there is some JSON object inside the string, how to convert that as well? Thanks for helping.
You can create like this,
public class SummaryResponse {
public String id;
public String bps_id;
public Summary summary;
public Message bps_message;
public String bps_image;
public Message error_message;
public String error_flags;
class Summary {
public String as_of_date;
public int bp_earned;
public String bp_balance;
public String bp_redeemed;
}
class Message {
public String eng;
public String chi;
}
}
you can call like this.
SummaryResponse summaryResponse = new Gson().fromJson([Your Json], SummaryResponse.class);
This a quick simple way to parse an array of Objects and also a single object it works for me when I am parsing json.
I believe it will only work as long as the json object is well formatted. I haven't experimented with a ill-formatted json object but that is because the api it request from was build by me, so I haven't had to worry about that
Gson gson = new Gson();
SummaryResponse[] data = gson.fromJson(jsonObj, SummaryResponse[].class);
I'm trying to convert a simple java object in JSON. I'm using google Gson library and it works, but I want a complete JSON object in this form:
{"Studente":[{ "nome":"John", "cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}
This is my class:
public class Studente {
private String nome;
private String cognome;
private String matricola;
private String dataNascita;
public Studente(){
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getMatricola() {
return matricola;
}
public void setMatricola(String matricola) {
this.matricola = matricola;
}
public String getDataNascita() {
return dataNascita;
}
public void setDataNascita(String dataNascita) {
this.dataNascita = dataNascita;
}
}
This is tester:
Studente x = new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson = new Gson();
String toJson = gson.toJson(x, Studente.class);
System.out.println("ToJSON "+toJson);
I have this in toJson: {"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}
The Json that you are trying to achieve is not the representation of a single Studente object, it is the representation of an object containing a list of Studente objects, that has a single entry.
So, you would need to create that extra object that contains the list of Studente objects, add the one instance to the list, and then serialize the object containing the list.
There's one minor issue, though. You are essentially asking for the wrapper object's list to have a property name that starts with a capital letter. This can be done, but breaks Java coding conventions.
It is best to write a wrapper for Students list. like this:
import java.util.ArrayList;
public class StudentWrapper {
private ArrayList<Studente> studente;
public StudentWrapper() {
studente = new ArrayList<Studente>();
}
public void addStudent(Studente s){
studente.add(s);
}
}
Code to convert to JSON :
Studente x=new Studente();
x.setCognome("Doe");
x.setNome("Jhon");
x.setMatricola("0512");
x.setDataNascita("14/10/1991");
Gson gson=new Gson();
StudentWrapper studentWrapper = new StudentWrapper();
studentWrapper.addStudent(x);
String toJson=gson.toJson(studentWrapper, StudentWrapper.class);
System.out.println("ToJSON "+toJson);
The output will be like this. The way you want it.
ToJSON {"studente":[{"nome":"Jhon","cognome":"Doe","matricola":"0512","dataNascita":"14/10/1991"}]}
Eclipse gave option to auto generate the toString method for every class.
Further leverage this facility, I am creating String Format Template to give as Json format when eclipse generate toString Method.
I used following String Format Template:
{ ${member.name()}:"${member.value}", ${otherMembers}}
now i generated toString method as following POJO but When i run this program i got result as and not a VALID JSON.
{ name:"null", reportees:"[1, 2, 3]", department:"[retail, banking, finance]", owns:"null", supplimentary:"null}
Code
public class TestPojo {
private String name;
private List<String> reportees;
private String[] department;
private Machine owns;
private List<Machine> supplimentary;
public static void main(String arg[]) {
TestPojo aTestPojo = new TestPojo();
aTestPojo.department = new String[] { "retail", "banking", "finance" };
aTestPojo.reportees = new ArrayList<String>() {
{
add("1");
add("2");
add("3");
}
};
System.out.print(aTestPojo);
}
public static class Machine {
private String machineName;
private String duties;
public String getMachineName() {
return machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
public String getDuties() {
return duties;
}
public void setDuties(String duties) {
this.duties = duties;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{ machineName:\"").append(machineName).append("\", duties:\"").append(duties).append("}");
return builder.toString();
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{ name:\"").append(name).append("\", reportees:\"").append(reportees).append("\", department:\"").append(Arrays.toString(department)).append("\", owns:\"").append(owns).append("\", supplimentary:\"").append(supplimentary).append("}");
return builder.toString();
}
}
With the help of #dvlcube idea. I built a "Eclipse Custom toString() builder" to generate toString method code to return a JSON formatted string of current object.
Follow the github for this solution Click [Eclipse toString_Builder for JSON](https://github.com/djaganathan/EclipseToStringBuilderForJson/blob/master/src/main/java/com/github/djaganathan/opensource/eclipse/util/JsonToStringBuilder.java,"Custom Eclipse toString() Builder")
Sample Testing Code
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.time.StopWatch;
import org.elasticsearch.common.collect.Lists;
public class TestPojo {
private String name;
private List<String> reportees;
private String[] department;
private Machine owns;
private List<Machine> supplimentary;
private int i = 10;
private Map<String, Machine> machineList = Maps.newConcurrentMap();
public static void main(String arg[]) {
TestPojo aTestPojo = new TestPojo();
aTestPojo.department = new String[] { "retail", "banking", "finance"};
aTestPojo.reportees = new ArrayList<String>() {
{
add("1");
add("2");
add("3");
}
};
Machine aMachine = new Machine("Train", "travel");
Machine aMachine1 = new Machine("Lorry", "Carrier");
aTestPojo.supplimentary = Lists.newArrayList(aMachine, aMachine1);
aTestPojo.machineList.put("Train", aMachine);
aTestPojo.machineList.put("Lorry", aMachine1);
System.out.print(aTestPojo);
}
public static class Machine {
private String machineName;
private String duties;
public Machine(String machineName, String duties) {
super();
this.machineName = machineName;
this.duties = duties;
}
public String getMachineName() {
return machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
public String getDuties() {
return duties;
}
public void setDuties(String duties) {
this.duties = duties;
}
#Override
public String toString() {
JsonToStringBuilder builder = new JsonToStringBuilder(this);
builder.append("machineName", machineName);
builder.append("duties", duties);
return builder.build();
}
}
#Override
public String toString() {
JsonToStringBuilder builder = new JsonToStringBuilder(this);
builder.append("name", name);
builder.append("reportees", reportees);
builder.append("department", department);
builder.append("owns", owns);
builder.append("supplimentary", supplimentary);
builder.append("i", i);
builder.append("machineList", machineList);
String value = builder.build();
return value;
}
}
While running this program i got the following JSON output
{"name": null,"reportees": ["1","2","3"],"department": ["retail","banking","finance"],"owns": null,"supplimentary": [{"machineName": "Train","duties": "travel"},{"machineName": "Lorry","duties": "Carrier"}],"i": 10,"machineList": {"Lorry": {"machineName": "Lorry","duties": "Carrier"},"Train": {"machineName": "Train","duties": "travel"}}}
It's not valid JSON because of the way arrays and collections are being printed ("[1,2,3]" instead of ["1","2","3"]).
Also, it wouldn't pass strict JSON validation because the field names should be quoted as well.
Eclipse's String Format Template can be very useful, but for full control it's better to create a builder class.
Here's a gist for doing just that. You can expand on it, and it works for your example class out of the box.
You can use this class to generate the toString() methods in Eclipse.
Recommended only for String values. Below expression gives you as a JSON toString generation.
{"${member.name()}":"${member.value}", "${otherMembers}"}
I've tried to do this in another project, and as per the tutorials I've seen, I know I am on the right track, but I cannot get this parsing correctly:
(Much Simplified) JSON Output:
{
"data":{
"info":{
"username": "something"
"email" : "something"
}
..
..
}
I am trying to get "username" and "email using the following classes:
class ProfileResponse {
static Data data;
public static Data getData() {
return data;
}
public static void setData(Data data) {
ProfileResponse.data = data;
}
}
Class Data {
#SerializedName("info")
static Info info;
public static Info getInfo() {
return info;
}
public static void setInfo(Info info) {
Data.info = info;
}
}
class Info {
#SerializedName("username")
static String username;
#SerializedName("email")
static String email;
public static String getUsername() {
return username;
}
public static String getEmail() {
return email;
}
}
and Deserializing the JSON String (could it be a problem that it's a String?) like so:
Gson gson = new Gson();
gson.fromJson(response, ProfileResponse.class);
if (Info.getUsername() == null
|| Info.getUsername().isEmpty()) {
System.out.println("NO USERNAME");
} else {
System.out.println("USERNAME: "
+ Info.getUsername());
}
This is printing "NO USERNAME" each time it's run.
static fields are by default excluded from serialization/deserialization.
Remove all the static keywords from your classes (fields and methods), call fromJson() correctly, and you will then get the result you're looking for.
Gson instantiates an instance of your class(es) from your JSON. After modifying your classes, you then will do:
ProfileResponse pr = gson.fromJson(response, ProfileResponse.class);