I want to create a run time String name in Java.
I tried something like using in JavaScript, but it is printing value like Status_Name_0 instead Open assigned to the String Status_Name_0
public static void GetPaymentStatusList(){
int i=0;
String Status_Name_0="Open";
String Status_ID_0="0";
String Status_Name_1="Approved";
String Status_ID_1="1";
String Status_Name_2="Denied";
String Status_ID_2="2";
for(i=0; i<3; i++){
Vars.PaymentStatusName_List.add("Status_Name_"+i);
Vars.PaymentStatusId_List.add("Status_ID_"+i);
}
}
but it is printing value like Status_Name_0 instead Open
Because that's what you added to the list...
add("Status_Name_"+i);
The way to get what you want would be a Map<String, String>
Map<String, String> map = new HashMap<>();
map.put("Status_Name_0", "Open");
// ...
for (int i=0;i<map.size();i++) {
String open = map.get("Status_Name_"+i);
}
How about you make some class instead, though?
public class PaymentStatus {
int id;
String name;
public PaymentStatus(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return String.format("%s[id: %d, name: %s]",
getClass().getSimpleName(), id, name);
}
}
And a List<PaymentStatus> would be preferred over appending integers to any variables.
public static List<PaymentStatus> getPaymentStatusList() {
List<PaymentStatus> list = new ArrayList<>();
paymentStatusList.add(new PaymentStatus(0, "Open"));
paymentStatusList.add(new PaymentStatus(1, "Approved"));
paymentStatusList.add(new PaymentStatus(2, "Denied"));
return list;
}
You're actually concatenating the string "Status_name_" with "0" which would result in "Status_name_0", a string, not a variable like Status_name_0. As far as I understand, you want the values of String_name_i (i= 0, 1, 2,....). To get that working, use String array.
String[] string_names = { "Open", "Approved", "Denied" };
int[] string_id = { 0, 1, 2 };
:You may not need a string_id array, as you can use the values of i in the for loop.
And add them in the list like:
Vars.PaymentStatusName_List.add(string_name[i]);
StringBuilder param = new StringBuilder();
param.append("shopid"
+ "=" + shopDetails.getShopId() + "&" + "username" + "=" + userDetail.getUserName() + "&" + "userid" + "=" + userDetail.getUserId() + "&");
for (int i = 0; i < brandList.size(); i++) {
param.append("brandId" + "[" + i + "]" + "=" + brandList.get(i).getBrandId()
+ "&" + "shortqua" + "[" + i + "]" + "=" + shortageStockList.get(i) + "&");
}
param.append("lattude" + "=" + String.valueOf(latitude) + "&" + "longitude" + "=" + String.valueOf(longitude));
Related
I want to return valid json string.
Ex:
{
"status":"Success",
"total_amt": "41",
"igst_amt": 14,
"sgst_amt": 0,
"cgst_amt": "12",
"cess_amt": 15
}
Expected:
{
"status":"Success",
"total_amt": "41",
"igst_amt": "14",
"sgst_amt": "0",
"cgst_amt": "12",
"cess_amt": "15"
}
I have wrote below code:
public String toString() {
return "{\"status\":\"" + status + "\",\"total_amt\":\"" + total_amt + "\",\"igst_amt\":\"" + igst_amt
+ "\",\"sgst_amt\":\"" + sgst_amt + "\",\"cgst_amt:\"" + cgst_amt + "\",\"cess_amt\":\"" + cess_amt + "\"}";
}
It is not returning valid JSON.
You can use a third party lib. This example uses GSON
class Result {
private String status;
#SerializedName("total_amt")
private int totalAmount;
#SerializedName("igst_amt")
private int igstAmount;
#SerializedName("sgst_amt")
private int sgstAmount;
#SerializedName("cgst_amt")
private int cgstAmount;
#SerializedName("cess_amt")
private int cessAmount;
public Result() {}
}
Result result = new Result();
// set your fields
String json = new Gson().toJson(result);
I hope igst_amt, sgst_amt and cess_amt are Integers.
So you add .toString() to them
public String toString() {
return "{\"status\":\"" + status + "\",\"total_amt\":\"" + total_amt + "\",\"igst_amt\":\"" + igst_amt.toString()
+ "\",\"sgst_amt\":\"" + sgst_amt.toString() + "\",\"cgst_amt:\"" + cgst_amt + "\",\"cess_amt\":\"" + cess_amt.toString() + "\"}";
}
Read about gson for returning json format. link to gson github
To simple use it you can:
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
final String string = "you string";
return gson.toJson(string);
I am using the following method to add url encoded (the encoding occurs inside another method) name/value pairs to the end of a url represented by the variable mUrl using the following code
public void addArgument(String name, String value){
String encName = urlEncode ( name ) ;
String encValue = urlEncode( value ) ;
String urlenc;
if ( argCount++ == 0 ){
urlenc = "?" + encName + "=" + encValue + "&";
mUrl = mUrl + urlenc;
argCount++;
} else {
urlenc = encName + "=" + encValue + "&";
mUrl = mUrl + urlenc;
}
}
The code works fine however the resulting url ends in "&". For example:
http://www.amazon.com?name=sam&age=5&
Is there a way I can adjust my code to get rid of the "&" on the end of the url?
Thanks
Add the & at the beginning instead of at the end:
public void addArgument(String name, String value) {
mUrl += (argCount++ == 0 ? "?" : "&") + urlEncode(name) + "=" + urlEncode(value);
}
How can insert this set of code in jtable. The problem is when I do md.addElement(id); it shows me a red underline on addElement()
Here is my code
public class hospitalisation extends javax.swing.JFrame {
DefaultTableModel md = new DefaultTableModel();
public hospitalisation() {
initComponents();
hospitalisationtable.setModel(md);
buttonGroup1.add(male);
buttonGroup1.add(female);
}
private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
String id = "id: " + idtxt.getText();
String name = "name: " + nametxt.getText();
String sex = "sex:";
String address = "address: " + addresstxt.getText();
String sdate = "sdate: " + sdatetxt.getText();
String room = "room: " + cs_room.getSelectedItem().toString();
String father = "father: " + fathertxt.getText();
String phone = "phone: " + phonetxt.getText();
String age = "age: " + agetxt.getText();
String edate = "edate " + edatetxt.getText();
if (female.getModel().isSelected() == true)
sex += female.getText();
else if (male.getModel().isSelected() == true)
sex += male.getText();
md.addElement(id);
md.addElement(name);
md.addElement(sex);
md.addElement(address);
md.addElement(sdate);
md.addElement(room);
md.addElement(father);
md.addElement(phone);
md.addElement(age);
md.addElement(edate);
}
it shows me a red underline on addElement()
this is because as you can see here there is no DefaultTableModel.addElement(String) in that class...
Consider instead taking a look at the doc and maybe consider one of the given methods
like
addColumn(Object columnName)
addColumn(Object columnName, Object[] columnData)
addColumn(Object columnName, Vector columnData)
addRow(Object[] rowData)
addRow(Vector rowData)
I am trying to turn a DTO to string to store in a database. I am calling:
ObjectMapper mapper = new ObjectMapper();
TypeFactory factory = mapper.getTypeFactory();
// type of key of response map
JavaType stringType = factory.constructType(String.class);
// type of value of response map
JavaType listOfDtosType = factory.constructCollectionType(ArrayList.class, SummonerRankedInfoDTOEntry.class);
// create type of map
JavaType responseType = factory.constructMapType(HashMap.class, stringType, listOfDtosType);
try {
assert json != null;
Map<String, List<SummonerRankedInfoDTOEntry>> response = new ObjectMapper().readValue(json, responseType);
summonerRankedInfoDTO.setIntegerSummonerRankedInfoDTOEntryMap(response);
logger.info("Json has been de-serialized" + summonerRankedInfoDTO.getIntegerSummonerRankedInfoDTOEntryMap());
} catch (IOException e) {
e.printStackTrace();
}
return summonerRankedInfoDTO;
on my DTO which is: http://codebeautify.org/javaviewer/cb5e233b.
Notice the fields:
LeagueDTOEntry {
division = 'V ', isFreshBlood = false, isHotStreak = false, isInactive = false, isVeteran = false, leaguePoints = 0, losses = 32, miniSeries = null, playerOrTeamId = 'TEAM - 77 b4b970 - 5e e2 - 11e4 - 9 d98 - c81f66db96d8 ', playerOrTeamName = 'Team Invertebrate ', wins = 32
}
the isFreshBlood, isHotStreak, isInactive and isVeteran fields.
I call the above code and log the string it returns, which is: https://jsonblob.com/56852fd6e4b01190df4650cd
All the fields above have lost the "is" part: freshBlood, hotStreak... etc.
I can post my DTOs but I've been looking for a long time and have no idea why it's changing their names. I don't think I ever named them without the "is" as the "is" is on the values returned from an API call.
Any help is appreciated, not sure how to make this question less confusing...
EDIT: My LeagueEntryDTO is:
private String division;
private boolean isFreshBlood;
private boolean isHotStreak;
private boolean isInactive;
private boolean isVeteran;
private int leaguePoints;
private MiniSeriesDTOEntry miniSeries;
private String playerOrTeamId;
private String playerOrTeamName;
private int wins;
private int losses;
#Override
public String toString() {
return "LeagueDTOEntry{" +
"division='" + division + '\'' +
", isFreshBlood=" + isFreshBlood +
", isHotStreak=" + isHotStreak +
", isInactive=" + isInactive +
", isVeteran=" + isVeteran +
", leaguePoints=" + leaguePoints +
", losses=" + losses +
", miniSeries=" + miniSeries +
", playerOrTeamId='" + playerOrTeamId + '\'' +
", playerOrTeamName='" + playerOrTeamName + '\'' +
", wins=" + wins +
'}';
}
If you really want to keep the is prefixes rather than respecting the standard JavaBean conventions, annotate your getters with (for example)
#JsonProperty("isInactive")
Also, your JSON logic is way too complex. You should just have to do
Map<String, List<SummonerRankedInfoDTOEntry>> response =
new ObjectMapper().readValue(
json,
new TypeReference<Map<String, List<SummonerRankedInfoDTOEntry>>>() {});
I need to write some information into the JSON file.
I have written the following function:
public String toJSON() {
StringBuffer sb = new StringBuffer();
sb.append("\"" + MyConstants.VEHICLE_LABEL + "\":");
sb.append("{");
sb.append("\"" + MyConstants.CAPACITY1_LABEL + "\": " + String.valueOf(this.getCapacity(0)) + ",");
sb.append("\"" + MyConstants.CAPACITY2_LABEL + "\": " + String.valueOf(this.getCapacity(1)) + ",");
sb.append("\"" + MyConstants.CAPACITY3_LABEL + "\": " + String.valueOf(this.getCapacity(2)));
sb.append("}");
return sb.toString();
}
However, I want to make this function more flexible. In particular, how should I change this code if the number of capacity units is not fixed (1, 2 or 3)?
I think that there should be a FOOR loop, however I am not sure how to implement it correctly.
Well you could do the append only if this.getCapacity(i) is not empty.
You could do something like this with a for loop
for(int i=0; i < max; i++) {
if(!StringUtils.isEmpty(String.valueOf(this.getCapacity(i)))){
sb.append("\"" + String.format(MyConstants.CAPACITY_LABEL, i) + "\": " + String.valueOf(this.getCapacity(i)) + ",");
}
}
where MyConstants.CAPACITY_LABEL is something like "capacity%d_label"
But, as azurefrog said, I would use a json parser to do this.
You can try the following class that follows the popular builder pattern:
public class JsonVehicleBuilder {
private StringBuilder builder;
/**
* Starts off the builder with the main label
*/
public JsonVehicleBuilder(String mainLabel) {
builder = new StringBuilder();
builder.append("\"").append(mainLabel).append("\":");
builder.append("{");
}
public JsonVehicleBuilder appendSimpleValue(String label, String value) {
builder.append("\"").append(label).append("\":").append(value).append(",");
return this;
}
/**
* Appends the closing bracket and outputs the final JSON
*/
public String build() {
builder.deleteCharAt(builder.lastIndexOf(",")); //remove last comma
builder.append("}");
return builder.toString();
}
}
And then in your main method you would call:
JsonVehicleBuilder jsonVehicleBuilder = new JsonVehicleBuilder(MyConstants.VEHICLE_LABEL);
jsonVehicleBuilder.appendSimpleValue(MyConstants.CAPACITY1_LABEL,String.valueOf(this.getCapacity(0)))
.appendSimpleValue(MyConstants.CAPACITY2_LABEL,String.valueOf(this.getCapacity(1)))
.appendSimpleValue(MyConstants.CAPACITY3_LABEL,String.valueOf(this.getCapacity(2)));
String json = jsonVehicleBuilder.build();
You can then keep chaining the appendSimpleValue method as long as you like.