I have the following JSON data:
[
{
"id": 4,
"siteName": "site1",
"addressLine1": "address1",
"addressLine2": "address2",
"town": "town1",
"postcode": "postcode1",
"contactName": "name1",
"contactNumber": "number1",
"contactEmail": "email1"
},
{
"id": 5,
"siteName": "site2",
"addressLine1": "address1",
"addressLine2": "address2",
"town": "town1",
"postcode": "postcode1",
"contactName": "name1",
"contactNumber": "number1",
"contactEmail": "email1"
},
]
I'm parsing the data but it simply outputs one long string. I'd like to access each element within each object.
UPDATE: I'm outputting the individual elements, but for some reason the 'id' property is considered a double?
Map<String,Object> jsonArr = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
java.util.List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)jsonArr.get("root");
for(Map<String, Object> obj : content) {
Log.p((int)obj.get("id"));
Log.p((String)obj.get("siteName"));
Log.p((String)obj.get("addressLine1"));
Log.p((String)obj.get("addressLine2"));
Log.p((String)obj.get("town"));
Log.p((String)obj.get("postcode"));
Log.p((String)obj.get("contactName"));
Log.p((String)obj.get("contactNumber"));
Log.p((String)obj.get("contactEmail"));
}
As you're using Codename One, parseJSON always returns a Map<String, Object>, but behaves differently when the root element is an array. In that case, the returned Map contains an object whose key is "root" which you then can iterate on to obtain the actual objects.
Map<String, Object> data = json.parseJSON(new InputStreamReader(
new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)data.get("root");
for(Map<String, Object> obj : content) {
Log.p(obj.getValue().toString());
}
For further info see the documentation for the parseJSON method.
You are getting an array of objects as it stats with [ and ends with ]. You have to try like this.
JSONArray jsonArr = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
for (int i = 0; i < jsonArr.length(); i++) {
String siteName = jsonArr.getJSONObject(i).getString("siteName");
System.out.println(siteName);
}
Related
How can I compare two JSON, one I get from the database and the second One from FrontEnd(means when I click on the edit button)? How can I compare these two JSON?
First Json
{
"id": 2,
"createdAt": "07-01-2021 15:26:16",
"updatedAt": "07-01-2021 15:26:16",
"offerAcceptedDate": "06-30-2021 07:14:00",
"offerAmount": 100000,
"offerDate": "06-30-2021 07:14:00",
"offerFile": "string",
"possibleCloseDate": "06-30-2021 07:14:00",
"remarks": "string",
"salesId": 8,
"status": "Active",
"contactId": 32,
"createdById": 1,
"offerAcceptedById": 1
}
2nd JSON
{
"createdAt": "09-01-2021 15:26:16",
"updatedAt": "10-01-2021 15:26:16",
"offerAcceptedDate": "06-30-2021 07:14:00",
"offerAmount": 500000,
"offerDate": "06-30-2021 07:14:00",
"offerFile": "string",
"possibleCloseDate": "06-30-2021 07:14:00",
"remarks": "string",
"salesId": 8,
"status": "Active",
"contactId": 32,
"createdById": 1,
"offerAcceptedById": 1
}
Also, compare these two JSON and also show activity what column" changed.
Like this:
createdAt: Changed
updatedAt: Changed
offeramount: Changed
1)First of all I get data from DB using findById(JPA Repository)
2)Compare Db field and request body field
like that :
LeadOffer leadOffer = leadOfferRepository.findById(offerId).orElse(null);
JsonObject jsonObject = new JsonObject();
JsonArray jsonArray= new JsonArray();
if (leadOffer.getAmount() != leadOfferRequest.getAmount())
{
offer.setAmount(leadOfferRequest.getAmount());
jsonObject.addProperty("amount",leadOfferRequest.getAmount() );
jsonObject1.addProperty("amount",leadOffer.getAmount() );
}
jsonArray.add(jsonObject);
You can use guava library for this purpose. For example :
String json1 = "{\"name\":\"ABC\", \"city\":\"XYZ\", \"state\":\"CA\"}";
String json2 = "{\"city\":\"XYZ\", \"street\":\"123 anyplace\", \"name\":\"ABC\"}";
Gson g = new Gson();
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> firstMap = g.fromJson(json1, mapType);
Map<String, Object> secondMap = g.fromJson(json2, mapType);
System.out.println(Maps.difference(firstMap, secondMap).entriesDiffering());
This shows the keys that are present in both the maps but have different values
i need to return a json, example
"employees": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
]
this is my code but i cant get the result
JSONArray array = new JSONArray();
ArrayList tipopropiedades = new ArrayList();
for (int i = 0; i < tp.length; i++) {
JSONObject detalle = new JSONObject();
TipoPropiedadTO ti = tp[i];
System.out.println(ti.getIdTipoCompra()+" "+ti.getNombreTipoCompra());
detalle.put("nombre",ti.getNombreTipoCompra().trim());
array.add(detalle);
}
the result of code when i get the alert(data) is
[{"nombre":"Casa"}, {"nombre":"Departamento"}, {"nombre":"Oficina"}, {"nombre":"Sitio Habitacional"}, {"nombre":"Sitio Comercial"}, {"nombre":"Sitio Industrial"}, {"nombre":"Agricola"}, {"nombre":"Parcela"}, {"nombre":"Bodega"}, {"nombre":"Estacionamiento"}]
What you need to return is a JSONObject containing that JSONArray as a field called "employees".
And you need to translate the fields in the objects you put into that JSONArray to have the proper names.
I'm trying to send API call using json-simple 1.1.1 and I save fields and values as a HashMap. I should send those parameters:
{ api_key : string,
product_id : string,
name : string,
tax_rates : array }
Here is a HashMap example:
HashMap<String,Object> arg = new HashMap<String, Object>();
arg.put("product_id","42");
arg.put("name", "EKOS");
arg.put("tax_rates", taxarray);
I saved taxarray as a HashMap as well:
HashMap<String, Object> taxarray = new HashMap<String, Object>();
taxarray.put("name","EKOS");
taxarray.put("type", "type_value_fixed");
taxarray.put("value", "56");
But when I execute an API call it reurns an error: Parameter 'tax_rates' is not valid. The required type of parameter is an array.
I had been trying to save taxarray HashMap as JSONArray as well. Could you please help me with this?
An additional question: how can I save 2 or more taxrates within one "tax_rates"? Here is an example:
HashMap<String,Object> arg = new HashMap<String, Object>();
arg.put("product_id","42");
arg.put("name", "EKOS");
arg.put("tax_rates", array [
taxarray1[],
taxarray2[]
]);
You should have something like this - Tax class:
public class Tax {
String name;
String type;
Integer[] values;
public Tax(String name, String type, Integer[] values) {
this.name = name;
this.type = type;
this.values = values;
}
}
And then use an array of objects of Tax class instead of HashMap for tax_rates : array.
This code using google json:
Map<String, Object> arg = new HashMap<String, Object>();
arg.put("product_id", "42");
arg.put("name", "EKOS");
arg.put("tax_rates",
new Tax[] { new Tax("EKOS", "type_value_fixed", new Integer[] { 1, 2, 3 }),
new Tax("ABC", "type_value_fixed", new Integer[] { 4, 5 }),
new Tax("DEF", "type_value_fixed", new Integer[] { 6, 7}) });
Gson gson = new Gson();
System.out.println(gson.toJson(arg));
Will give you such json:
{
"product_id": "42",
"name": "EKOS",
"tax_rates": [
{
"name": "EKOS",
"type": "type_value_fixed",
"values": [
1,
2,
3
]
},
{
"name": "ABC",
"type": "type_value_fixed",
"values": [
4,
5
]
},
{
"name": "DEF",
"type": "type_value_fixed",
"values": [
6,
7
]
}
]
}
tax_rates has to be an array, so do this:
List<Double> taxRates = new ArrayList<Double>();
taxRates.add(19);
taxRates.add(17.5);
Map<String,Object> arg = new HashMap<String, Object>();
arg.put("product_id","42");
arg.put("name", "EKOS");
arg.put("tax_rates", taxRates);
I'm getting this error when attempting to parse some JSON previously generated with Jackson. I generate the JSON like so
String ret = "";
ret = mapper.writeValueAsString(message.getPayload());
message.setPayload(ret);
Where message.getPayload() is a HashMap, in this instance containing two strings and a List of various objects. This creates the following malformed JSON
{
"user" : "john d example",
"items" : [ {
"val" : 99.5,
"id" : "phone",
"qty" : 1
}, {
"val" : 15.5,
"id" : "wine",
"qty" : 4
} ],
"address" : "123 example street"
}
Which throws an exception when examined thusly
Map<String, Object> ret = new HashMap<String, Object>();
String s = (String)message.getPayload();
ret = mapper.readValue(s, new TypeReference<Map<String, String>>(){});
How should I properly write this Map to JSON?
TypeReference<Map<String, String>> should be TypeReference<Map<String, Object>>. Jackson is attempting to parse the values as Strings rather than Lists because that is what it expects based on the TypeReference you passed in.
i have a json-file called "user.json". Now i want to add a new user. I know how to get the content of the file and put it in a String, but i dont know how to add new content correctly. "jsonString" is the content of "user.json"
JSONParser parser = new JSONParser();
Object object = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) object;
jsonObject.put("name", name);
jsonObject.put("region", region);
jsonObject.put("v1", v1);
jsonObject.put("v2", v2);
System.out.println(jsonObject.toJSONString());
The output is:
{
"v1": false,
"v2": false,
"name": "test",
"region": "",
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
}
]
}
But it should be:
{
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
},
{
"v1": false,
"v2": false,
"name": "test",
"region": ""
}
]
}
Does somebody know how to do it right?
I looked it up but all the examples are not working for me, because when i try
JSONObject object = new JSONObject(jsonString);
or
JSONArray array = new JSONArray(jsonString);
i always get "the constructor ist undefined".
Edit:
content of user.json
{"user":[
{"name":"Testuser1", "region":"A", "v1":"false", "v2":"false"},
{"name":"Testuser2", "region":"B", "v1":"true", "v2":"true"},
{"name":"Testuser3", "region":"B", "v1":"false", "v2":"false"},
{"name":"Testuser4", "region":"A", "v1":"true", "v2":"true"},
{"name":"Testuser5", "region":"A", "v1":"false", "v2":"false"}
]}
Edit2:
I solved the problem
Object object = parser.parse(new FileReader(classLoader.getResource("user.json").getFile()));
JSONObject jsonObject = (JSONObject) object;
JSONArray array = (JSONArray) jsonObject.get("user");
JSONObject newObject = new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
array.add(newObject);
Map<String, JSONArray> map = new HashMap<>();
map.put("\"user\"", array);
String mapInhalt = map.toString();
if (mapInhalt.contains("=")) {
System.out.println("yop");
mapInhalt.replaceFirst("=", ":");
}
System.out.println(mapInhalt);
it seems you are adding fields to your jsonObject, and what you want to do it basically adding the new object to the inner json array (in this case field is called "user"
try this:
JSONObject newObject=new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
jsonObject.getJSONArray("user").add(newObject)
you can use fromObject() method:
JSONObject json = JSONObject.fromObject(jsonStr);
JSONArray jsonArry = JSONArray.fromObject(jsonStr);