Map JSON array into java object array - java

I'm calling API and getting the response as a JSON array I need to map that array into Java object array. Here I've defined the model class below you can see API JSON array, Model class and the way I try to map JSON array into Java object array. I need to make sure if this approach is correct or not.
API response JSON array
[
{
"sanctionId": 594,
"listId": "SDN",
"listType": "SANCTION",
"publisher": "OFAC",
"addedDate": "2022-02-11T04:52:59.775+0000",
"programs": "CUBA",
"name": " CUBA CIGARS TRADE",
"title": null,
"type": "Entity",
"contacts": [
{
"id": 361,
"address": " ",
"city": "",
"state_province": "",
"country": "Italy",
"remarks": null
}
],
"identities": null,
"remarks": null,
"other": null,
"score": 2.1659167
},
{
"sanctionId": 602,
"listId": "SDN",
"listType": "SANCTION",
"publisher": "OFAC",
"addedDate": "2022-02-11T04:52:59.779+0000",
"programs": "CUBA",
"name": " CUBA N CIGARS TRADE",
"title": null,
"type": "Entity",
"contacts": [
{
"id": 361,
"address": " ",
"city": "",
"state_province": "",
"country": "Italy",
"remarks": null
}
],
"identities": null,
"remarks": null,
"other": null,
"score": 1.9129416
}
]
Model Class(here I've omitted getters and setters) :
public class SanctionInquiryResponse {
private String sanctionId="";
private String listId="";
private String listType="";
private String publisher="";
private String addedDate="";
private String programs="";
private String name="";
private String title="";
private String type="";
private String identities="";
private String remarks="";
private String other="";
private String score="";
private List<Contacts> contacts = null;
}
public class Contacts {
private String id = "";
private String address = "";
private String city = "";
private String state_Province = "";
private String country = "";
private String remarks = "";
}
Here is the way I'm trying to map the JSON array into the Java object array
String url="http://localhost:8070/getObject";
ObjectMapper mapper = new ObjectMapper();
//String jsonInString = mapper.writeValueAsString(openCaseRequest);
Client client = Client.create();
client.setConnectTimeout(120*1000);
client.setReadTimeout(120*1000);
WebResource webResource = client.resource(url);
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);
String output = response.getEntity(String.class);
JSONArray jsonArray = new JSONArray(output);
Gson gson = new Gson();
for (int i = 0; i < jsonArray.length(); i++) {
sanctionInquiryResponse = gson.fromJson(jsonArray.getJSONObject(i).toString() ,SanctionInquiryResponse.class);
}

Related

JSON, data can have object and array and use data class for all

When trying to process JSON, I recive Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
This JSON is a client with array in data but i want to use the same data class for other for example employee, but I need that data can store different classes
{
"data": [
{
"client": "PAL",
"organization": "*",
"organization_info": {
"name": "*",
"searchKey": "0",
"id": "0"
},
"id": "*****",
"searchKey": "AJ23",
"commercialName": "MANOLO",
"fiscalName": "MANOLO",
"locations": [{
"address": "NUEVA",
"city": "SEVILLA",
"zipCode": "00000",
"country": "ES"}]
},
{
"client": "LAC",
"organization": "*",
"organization_info": {
"name": "*",
"searchKey": "0",
"id": "0"
},
"id": "*****",
"searchKey": "0ASD13",
"commercialName": "DANI",
"fiscalName": "DANI",
"locations": [{
"address": "FONTANA",
"city": "VALLADOLID",
"zipCode": "00000",
"country": "ES"
}]
}]
}
This JSON has a data object since it only has one result
{
"data": {
"client": "PAL",
"organization": "*",
"organization_info": {
"name": "*",
"searchKey": "0",
"id": "0"
},
"id": "*****",
"searchKey": "AJ2",
"commercialName": "MANOLO",
"fiscalName": "MANOLO",
"locations": [
"address": "NUEVA",
"city": "SEVILLA",
"zipCode": "00000",
"country": "ES"
}]
}
}
The idea of the Data class is that it be generic to be able to call different classes Customer, Provider, etc. from the main class.
public class Data<T> {
#SerializedName("data")
private final List<T> data;
String links;
public Data(List<T> data) {
super();
this.data = data;
}
public List<T> getData() {
return data;
}
//get and set method
public class Client {
private String client;
private String organization;
private Org_info organization_info;
private String id;
private String fiscalName;
private String searchKey;
private String commercialName;
private String phone;
private String email;
private ArrayList<Locations> locations;
public Cliente(Org_info organization_info, String client, String organization, String id, String fiscalName, String searchKey,String phone, String email,
String commercialName,ArrayList<Locations> locations) {
super();
this.organization_info=organization_info;
this.client = client;
this.organization = organization;
this.id = id;
this.fiscalName = fiscalName;
this.searchKey = searchKey;
this.commercialName = commercialName;
this.locations = locations;
}
//get and set method
How can I make the data class generic, and be able to store JSON data with the data node from both clients and providers, while receiving an array of data or a data object?
public static void main(String[] args){
conection();
InputStreamReader inputStreamReader = new InputStreamReader(http.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = br.read()) != -1) {
sb.append((char) cp);
}
String output = sb.toString();
final Type tpEnvClient = new TypeToken<Data<Client>>(){}.getType();
final Data<Client> envEmp = new Gson().fromJson(output, tpEnvClient);
When trying to store an array I get an error because I can't store a list of clients.

How can I get inside info object using volley in android java

this is the json data and i want to display the info object using volley in android java i hope you can answer this question thank you
"data": {
"type": "customer",
"name": "Sasmple name",
"phone": "1234567",
"email": "sample#gmail.com",
"email_verified_at": null,
"created_at": "2021-05-04T08:24:49.000000Z",
"updated_at": "2021-05-04T08:24:49.000000Z",
"info": {
"id": 63,
"user_id": 381,
"fname": "Sample",
"mname": null,
"lname": "Name",
"gender": null,
"image": null,
"birthdate": null,
"address": "Sample, Sample City (capital), Sample",
"address_code": "{\"region\":\"07\",\"province\":\"0722\",\"citymun\":\"072217\",\"barangay\":\"072217027\"}",
"bank_number": "17171717171717171717",
"bank_name": "Sample bank",
"created_at": "2021-05-04T08:24:49.000000Z",
"updated_at": "2021-05-04T08:24:49.000000Z"
}
}
and this is my code that i used
JSONObject json= null;
try {
json = new JSONObject("info");
for(int i=0; i<json.length(); i++){
JSONObject item = json.getJSONObject(String.valueOf(json));
String province_id = item.getString("id");
String province_code = item.getString("fname");
String province_desc = item.getString("lname");
String province_regcode = item.getString("address");
String province_citycode = item.getString("address_code");
}
} catch (JSONException e) {
e.printStackTrace();
}
Please read more about JSON Object and Json Array here
To answer for your question
try {
JSONObject jsonData = new JSONObject(httpStringResponse);
JSONObject infoItem = json.getJSONObject("info");
String province_id = infoItem.getString("id");
String province_code = infoItem.getString("fname");
String province_desc = infoItem.getString("lname");
String province_regcode = infoItem.getString("address");
String province_citycode = infoItem.getString("address_code");
} catch (JSONException e) {
e.printStackTrace();
}

Reading data from JSON

Here is my JSON response
{
"data": [
{
"id": "txn_17pHAkI4mX5ntfze4If5wIxW",
"source": "tr_17pHAkI4mX5ntfzeIfNucubD",
"amount": -100000,
"currency": "usd",
},
{
"id": "txn_17pH21I4mX5ntfzesrhdZwyf",
"source": "tr_17pH21I4mX5ntfzeKLd0SWw0",
"amount": -100000,
},
{
"id": "txn_17pGVRI4mX5ntfzeBQPCWZZg",
"source": "tr_17pGVRI4mX5ntfzegJNe1r4o",
"amount": -100000,
"currency": "usd"
}
],
},
"url": "/v1/balance/history",
"count": null
}
I want to get "amount" and "id" from these three list.
How to do it in java?
Look into Google's Gson.
You need to create a class that represents the json data.
class Response {
class Data {
public String id;
public String source;
public int amount;
public String currency;
}
public Data[] data;
public String url;
public int count;
}
Then read the data into a variable.
String json = "your json here";
Gson gson = new Gson();
Response response = gson.fromJson(json, Response.class);
for(Data d : response.data) {
System.out.println(d.id);
System.out.println(d.amount);
}

Getting JSON value from HTTP Request using GSON with Java

I need to get the lat and lng cords as separate string values. I decided to use GSON to help with this but am having issues getting the points. I'd prefer not to add any extra classes but it's not a deal breaker. I don't even care to use an easier solution without GSON if there is one.
Below is what I tried.
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws InterruptedException, IOException, JSONException {
JSONObject json = readJsonFromUrl("http://open.mapquestapi.com/geocoding/v1/address?key=Fmjtd|luu821ual9,8w=o5-94aaqy&location=1448south4thstreetlouisvilleky");
System.out.println(json.toString());
System.out.println(json.get("results"));
}
I can get the results string but not just the lat or lng. Plus it uses extra classes I was trying to avoid. Below is what the JSON returned from the URL looks like.
{
"info": {},
"options": {},
"results": [
{
"providedLocation": {
"location": "address here"
},
"locations": [
{
"street": "address here",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"adminArea5": "city name",
"adminArea5Type": "City",
"adminArea4": "County name",
"adminArea4Type": "County",
"adminArea3": "State name",
"adminArea3Type": "State",
"adminArea1": "US",
"adminArea1Type": "Country",
"postalCode": "zip here",
"geocodeQualityCode": "P1AAX",
"geocodeQuality": "POINT",
"dragPoint": false,
"sideOfStreet": "N",
"linkId": "0",
"unknownInput": "",
"type": "s",
"latLng": {
"lat": 90.227222,
"lng": -90.762007
},
"displayLatLng": {
"lat": 90.227222,
"lng": -90.762007
},
"mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=111111111,160&pois=purple4"
}
]
}
]
}
JsonParser parser = new JsonParser();
JsonObject o = parser.parse(jsonStr).getAsJsonObject();
JsonElement latLng = o.get("results")
.getAsJsonArray().get(0)
.getAsJsonObject().get("locations")
.getAsJsonArray().get(0)
.getAsJsonObject().get("latLng");
Parse json String as Jsonobject, and get value one by one. but I think the fastest way is creating a model to map the Json String Object.

Convert string to JSON array

I have the following string of a JSON from a web service and am trying to convert this to a JSONarray
{
"locations": [
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
},
{
"lat": "23.053",
"long": "72.629",
"location": "ABC",
"address": "DEF",
"city": "Ahmedabad",
"state": "Gujrat",
"phonenumber": "1234567"
}
]
}
I validated this String online, it seems to be correct. Now I am using the following code in android development to utilise
JSONArray jsonArray = new JSONArray(readlocationFeed);
This throws exception a type mismatch Exception.
Here you get JSONObject so change this line:
JSONArray jsonArray = new JSONArray(readlocationFeed);
with following:
JSONObject jsnobject = new JSONObject(readlocationFeed);
and after
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
Input String
[
{
"userName": "sandeep",
"age": 30
},
{
"userName": "vivan",
"age": 5
}
]
Simple Way to Convert String to JSON
public class Test
{
public static void main(String[] args) throws JSONException
{
String data = "[{\"userName\": \"sandeep\",\"age\":30},{\"userName\": \"vivan\",\"age\":5}] ";
JSONArray jsonArr = new JSONArray(data);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj);
}
}
}
Output
{"userName":"sandeep","age":30}
{"userName":"vivan","age":5}
Using json lib:-
String data="[{"A":"a","B":"b","C":"c","D":"d","E":"e","F":"f","G":"g"}]";
Object object=null;
JSONArray arrayObj=null;
JSONParser jsonParser=new JSONParser();
object=jsonParser.parse(data);
arrayObj=(JSONArray) object;
System.out.println("Json object :: "+arrayObj);
Using GSON lib:-
Gson gson = new Gson();
String data="[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\",\"D\":\"d\",\"E\":\"e\",\"F\":\"f\",\"G\":\"g\"}]";
JsonParser jsonParser = new JsonParser();
JsonArray jsonArray = (JsonArray) jsonParser.parse(data);
you will need to convert given string to JSONObject instead of JSONArray because current String contain JsonObject as root element instead of JsonArray :
JSONObject jsonObject = new JSONObject(readlocationFeed);
String b = "[" + readlocationFeed + "]";
JSONArray jsonArray1 = new JSONArray(b);
jsonarray_length1 = jsonArray1.length();
for (int i = 0; i < jsonarray_length1; i++) {
}
or convert it in JSONOBJECT
JSONObject jsonobj = new JSONObject(readlocationFeed);
JSONArray jsonArray = jsonobj.getJSONArray("locations");
Try this piece of code:
try {
Log.e("log_tag", "Error in convert String" + result.toString());
JSONObject json_data = new JSONObject(result);
String status = json_data.getString("Status");
{
String data = json_data.getString("locations");
JSONArray json_data1 = new JSONArray(data);
for (int i = 0; i < json_data1.length(); i++) {
json_data = json_data1.getJSONObject(i);
String lat = json_data.getString("lat");
String lng = json_data.getString("long");
}
}
}
if the response is like this
"GetDataResult": "[{\"UserID\":1,\"DeviceID\":\"d1254\",\"MobileNO\":\"056688\",\"Pak1\":true,\"pak2\":true,\"pak3\":false,\"pak4\":true,\"pak5\":true,\"pak6\":false,\"pak7\":false,\"pak8\":true,\"pak9\":false,\"pak10\":true,\"pak11\":false,\"pak12\":false}]"
you can parse like this
JSONObject jobj=new JSONObject(response);
String c = jobj.getString("GetDataResult");
JSONArray jArray = new JSONArray(c);
deviceId=jArray.getJSONObject(0).getString("DeviceID");
here the JsonArray size is 1.Otherwise you should use for loop for getting values.
It's a very simple way to convert:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
class Usuario {
private String username;
private String email;
private Integer credits;
private String twitter_username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getCredits() {
return credits;
}
public void setCredits(Integer credits) {
this.credits = credits;
}
public String getTwitter_username() {
return twitter_username;
}
public void setTwitter_username(String twitter_username) {
this.twitter_username = twitter_username;
}
#Override
public String toString() {
return "UserName: " + this.getUsername() + " Email: " + this.getEmail();
}
}
/*
* put string into file jsonFileArr.json
* [{"username":"Hello","email":"hello#email.com","credits"
* :"100","twitter_username":""},
* {"username":"Goodbye","email":"goodbye#email.com"
* ,"credits":"0","twitter_username":""},
* {"username":"mlsilva","email":"mlsilva#email.com"
* ,"credits":"524","twitter_username":""},
* {"username":"fsouza","email":"fsouza#email.com"
* ,"credits":"1052","twitter_username":""}]
*/
public class TestaGsonLista {
public static void main(String[] args) {
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(
"C:\\Temp\\jsonFileArr.json"));
JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement str = jsonArray.get(i);
Usuario obj = gson.fromJson(str, Usuario.class);
System.out.println(obj);
System.out.println(str);
System.out.println("-------");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can do the following:
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
If having following JSON from web service, Json Array as a response :
[3]
0: {
id: 2
name: "a561137"
password: "test"
firstName: "abhishek"
lastName: "ringsia"
organization: "bbb"
}-
1: {
id: 3
name: "a561023"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}-
2: {
id: 4
name: "a541234"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}
have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .
List<User> list = new ArrayList<User>();
JSONArray jsonArr = new JSONArray(response);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
ObjectMapper mapper = new ObjectMapper();
User usr = mapper.readValue(jsonObj.toString(), User.class);
list.add(usr);
}
mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .

Categories

Resources