Return string in valid JSON - java

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

Related

Building String name using concatenation with a for loop

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

Parsing JSON string in Java android

I want to extract elements (state,county ) from this JSON string :
I am trying to parse a JSON string in java to have the individual value printed separately. But while making the program run I get nothing.
"place": [
{
"address": {
"country_code": "fr",
"country": "France",
"state": "Normandie",
"county": "Calvados"
},
"icon": "http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png",
"importance": 0.74963706049207,
"type": "administrative",
"class": "boundary",
"display_name": "Calvados, Normandie, France",
"lon": "-0.24139500722798",
"lat": "49.09076485",
"boundingbox": [
"48.7516623",
"49.4298653",
"-1.1597713",
"0.4466332"
],
"osm_id": "7453",
"osm_type": "relation",
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
"place_id": "158910871"
}
]
any help would be appreciated. thanks.
these is my android code :
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
adresse = object3.getJSONObject("place").getJSONObject("address").getString("state");
Log.e("mylog",adresse);
}
In your JSON string, "place" is a JSONArray and its containing another JSONObject. Get "place" value as below:
// Place
JSONArray place = jsonObj.getJSONArray("place");
Get "address" value as below:
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
Get "countryCode", "country", "state" and "county" value as below:
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Here is the fully working code. Try this:
public void parseJson() {
// Your JOSON string
String jsonStr = "{\"place\": [\n" +
" {\n" +
" \"address\": {\n" +
" \"country_code\": \"fr\",\n" +
" \"country\": \"France\",\n" +
" \"state\": \"Normandie\",\n" +
" \"county\": \"Calvados\"\n" +
" },\n" +
" \"icon\": \"http://nominatim.openstreetmap.org/images/mapicons/poi_boundary_administrative.p.20.png\",\n" +
" \"importance\": 0.74963706049207,\n" +
" \"type\": \"administrative\",\n" +
" \"class\": \"boundary\",\n" +
" \"display_name\": \"Calvados, Normandie, France\",\n" +
" \"lon\": \"-0.24139500722798\",\n" +
" \"lat\": \"49.09076485\",\n" +
" \"boundingbox\": [\n" +
" \"48.7516623\",\n" +
" \"49.4298653\",\n" +
" \"-1.1597713\",\n" +
" \"0.4466332\"\n" +
" ],\n" +
" \"osm_id\": \"7453\",\n" +
" \"osm_type\": \"relation\",\n" +
" \"licence\": \"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright\",\n" +
" \"place_id\": \"158910871\"\n" +
" }\n" +
" ]}";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Place
JSONArray place = jsonObj.getJSONArray("place");
// Address
JSONObject address = place.getJSONObject(0).getJSONObject("address");
String countryCode = address.getString("country_code");
String country = address.getString("country");
String state = address.getString("state");
String county = address.getString("county");
Log.d("SUCCESS", "State: " + state + " Country: " + country + " County: " + county);
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
}
Hope this will help~
The first thing you need is to make sure you are receiving this string or not. I am assuming you are trying to fetch it from some URL.
To fetch the JSON you can use the following code snippet.
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
You need to pass your URL to this function. And if calling this method is displaying the JSON data that you are expecting then the first part is done. You have the JSON string in onPostExecute() method.
Now you can easily parse this string if it contains a valid JSON data. But the JSON that you shown in your question does not seems a valid JSON. I guess it is only part of a big JSON file. So if you need the exact code to parse your JSON post the full JSON.
Pat parsing is very easy. If the json you have is an object create an instance of JSONObject if it is an array create an instance of JSONObject.
Then you can easily get the keys if it is an object. Or you can traverse through items if it is an array.
For more details you can check this JSON Parsing in Android post.
Change for this:
JSONObject objectPremium = new JSONObject(String.valueOf(result));
String premium = objectPremium.getString("premium");
JSONArray jArray1 = objectPremium.getJSONArray("premium");
for(int i = 0; i < jArray1.length(); i++)
{
JSONObject object3 = jArray1.getJSONObject(i);
JSONArray placeArray = object3.getJSONArray("place")
JSONObject addressObject = placeArray.getJSONObject("address");
adress = addressObject.getString("state");
Log.e("mylog",adresse);
}
If your initial part of the JSON Parsing code is correct, then this should work!
JSONArray jArray = new JSONArray(result);
JSONObject objectPremium = jArray.get(0);
JSONObject json = jsonObject.getJSONObject("address");
String state = json.getString("state");
String country = json.getString("country");
Check this code,
this is how you parse and store in a list
String jsonStr = //your json string
HashMap<String, String> addressList= new HashMap<>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray address = jsonObj.getJSONArray("address"); // for the address
// looping through All that
for (int i = 0; i < address.length(); i++) {
JSONObject c = address.getJSONObject(i);
String country_code= c.getString("country_code");
String country= c.getString("country");
String state= c.getString("state");
String county = c.getString("county");
// adding each child node to HashMap key => value
address.put("country_code", country_code);
address.put("country", country);
address.put("state", state);
address.put("county", county);
// adding address to address list
addressList.add(address);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}

Complex JSON deserialization with gson Java

How can I deserialize this complex JSON .
I want to access all objects and read.
For example SelectionId and AdditionalPriceInfo fields by indexing.
get(0).getSelectionId() --> d51d38c9-6e51-473c-b843-f24fef632f89
{
"Status": 0,
"Message": "",
"Result": {
"HasMore": "False",
"Itineraries": [
{
"SelectionId": "d51d38c9-6e51-473c-b843-f24fef632f89",
"AdditionalPriceInfo": null,
"Trips": [
{
"TotalTravelTime": "02:00:00"
}
]
},
{
"SelectionId": "ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c",
"AdditionalPriceInfo": null,
"Trips": [
{
"TotalTravelTime": "01:23:00"
}
]
}
],
"SearchOriginCityText": "Long Beach",
"SearchOriginAirportCode": "LGB",
"SearchDestinationCityText": "SFO",
"SearchDestinationAirportCode": "SFO"
}
}
My code so far for accessing all I want:
Gson gson2 = new Gson();
AirJson airJson = gson2.fromJson(airFullResult3, AirJson.class);
Itineraries itineraries = gson2.fromJson(airFullResult3, Itineraries.class);
Result result = gson2.fromJson(airFullResult3, Result.class);
//Having null instead SFO
System.out.println(result.getSearchDestinationAirportCode());
//Having null
System.out.println(itineraries.getAdditionalPriceInfo());
When I split my JSON, I can access the values that I want.
{
"Itineraries": [{
"SelectionId": "d51d38c9-6e51-473c-b843-f24fef632f89",
"AdditionalPriceInfo": null
}, {
"SelectionId": "dda40b80-d8e4-4b76-9f78-83297b52afe9",
"AdditionalPriceInfo": null
}]
}
Successful code and I access values.
JsonParser parser = new JsonParser();
JsonObject rootObject = parser.parse(airFullResult).getAsJsonObject();
JsonElement projectElement = rootObject.get("Itineraries");
Type listofObject = new TypeToken<List<Itineraries>>(){}.getType();
List<Itineraries> itiList = gson2.fromJson(projectElement, listofObject);
//Having d51d38c9-6e51-473c-b843-f24fef632f89 as a result
//which is great
System.out.println(itiList.get(0).getSelectionId());
When I use the same code for first unallocated JSON, doesn't work and having java.lang.NullPointerException as error
you need to build one object with a couple of child objects which represents your json-structure. the following code works! (testet with java 8, and gson 2.6.2)
#Test
public void test() {
Gson gson = new Gson();
Data data = gson.fromJson(getJson(), Data.class);
Assert.assertNotNull(data);
Assert.assertNotNull(data.result);
Assert.assertNotNull(data.result.itineraries);
Assert.assertEquals(2, data.result.itineraries.length);
Assert.assertEquals("d51d38c9-6e51-473c-b843-f24fef632f89", data.result.itineraries[0].selectionId);
Assert.assertEquals("ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c", data.result.itineraries[1].selectionId);
}
public class Data {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("HasMore")
String hasMore;
#SerializedName("Itineraries")
Itineraries[] itineraries;
#SerializedName("SearchOriginCityText")
String searchOriginCityText;
#SerializedName("SearchOriginAirportCode")
String searchOriginAirportCode;
#SerializedName("SearchDestinationCityText")
String searchDestinationCityText;
#SerializedName("SearchDestinationAirportCode")
String searchDestinationAirportCode;
}
public class Itineraries {
#SerializedName("SelectionId")
String selectionId;
#SerializedName("AdditionalPriceInfo")
String additionalPriceInfo;
#SerializedName("Trips")
Trips[] trips;
}
public class Trips {
#SerializedName("TotalTravelTime")
String totalTravelTime;
}
private String getJson() {
String json = "";
json += "{";
json += " \"Status\": 0,";
json += " \"Message\": \"\",";
json += " \"Result\": {";
json += " \"HasMore\": \"False\",";
json += " \"Itineraries\": [";
json += " {";
json += " \"SelectionId\": \"d51d38c9-6e51-473c-b843-f24fef632f89\",";
json += " \"AdditionalPriceInfo\": null,";
json += " \"Trips\": [";
json += " {";
json += " \"TotalTravelTime\": \"02:00:00\"";
json += " }";
json += " ]";
json += " },";
json += " {";
json += " \"SelectionId\": \"ff44d76a-a4c8-4aff-9f9d-6db4e1f3092c\",";
json += " \"AdditionalPriceInfo\": null,";
json += " \"Trips\": [";
json += " {";
json += " \"TotalTravelTime\": \"01:23:00\"";
json += " }";
json += " ]";
json += " }";
json += " ],";
json += " \"SearchOriginCityText\": \"Long Beach\",";
json += " \"SearchOriginAirportCode\": \"LGB\",";
json += " \"SearchDestinationCityText\": \"SFO\",";
json += " \"SearchDestinationAirportCode\": \"SFO\"";
json += " }";
json += "}";
return json;
}

ObjectMapper writeValueAsString() changing key names when writing to String

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>>>() {});

How to parse json string created by stringify function in javascript?

I want to parse the json string in java class (.java) created by stringify() function in javascript. I know to parse the string like:
String JSON_DATA
= "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
but how to parse this string?
var IO = {
//returns array with storable google.maps.Overlay-definitions
IN: function(arr, //array with google.maps.Overlays
encoded//boolean indicating whether pathes should be stored encoded
) {
var shapes = [],
goo = google.maps,
shape, tmp;
for (var i = 0; i < arr.length; i++)
{
shape = arr[i];
tmp = {type: this.t_(shape.type), id: shape.id || null};
switch (tmp.type) {
case 'CIRCLE':
tmp.radius = shape.getRadius();
tmp.geometry = this.p_(shape.getCenter());
break;
case 'MARKER':
tmp.geometry = this.p_(shape.getPosition());
break;
case 'RECTANGLE':
tmp.geometry = this.b_(shape.getBounds());
break;
case 'POLYLINE':
tmp.geometry = this.l_(shape.getPath(), encoded);
break;
case 'POLYGON':
tmp.geometry = this.m_(shape.getPaths(), encoded);
break;
}
shapes.push(tmp);
}
return shapes;
}
and the string formed to be parsed is:
[{"type":"CIRCLE","id":null,"radius":1730.4622192451884,"geometry":[32.3610810916614,50.91339111328125]},{"type":"CIRCLE","id":null,"radius":1831.5495077322266,"geometry":[32.35528086804335,50.997161865234375]},{"type":"CIRCLE","id":null,"radius":1612.2461023303567,"geometry":[32.34454947365649,51.011924743652344]}]
You can use Gson or Jackson for this. Create a POJO that hold the data and use these libs. An eg with Gson
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
class JsonData {
private String type;
private String id;
private double radius;
private List<Double> geometry;
//Getters & Setters
}
public class JsonParser {
public static void main(String[] args) {
String json = "[{\"type\":\"CIRCLE\",\"id\":null,\"radius\":1730.4622192451884,\"geometry\":[32.3610810916614,50.91339111328125]},{\"type\":\"CIRCLE\",\"id\":null,\"radius\":1831.5495077322266,\"geometry\":[32.35528086804335,50.997161865234375]},{\"type\":\"CIRCLE\",\"id\":null,\"radius\":1612.2461023303567,\"geometry\":[32.34454947365649,51.011924743652344]}]";
Type listType = new TypeToken<List<JsonData>>() {}.getType();
List<JsonData> disputeSummaryArraylistobjectList = new Gson().fromJson(json, listType);
System.out.println(disputeSummaryArraylistobjectList);
}
}
You will need a JSON parser for Java like GSON or Jackson.
There are two strategies for parsing:
Creating Java objects and let the JSON parsers map elements in the input to fields
Iterating over the generic JSON data structure which the parser returns
The documentation of both projects contain lots of examples how to achieve either.

Categories

Resources