I have the following scenario
"sections": [
{
"id": XXXX,
"tipology": "TIPOLOGY"
},
{
"id": XXXX,
"tipology": "TIPOLOGY"
},
{"num": 2}
],
I'm using JSONArray and JSONObject. Is there some way to do this?
"sections": [
"num": 2,
{
"id": XXXX,
"tipology": "TIPOLOGY"
},
{
"id": XXXX,
"tipology": "TIPOLOGY"
},
],
I believe you are trying to count the array within. I think you can do it below way.
{
"sections": [{
"id": "XXXX",
"tipology": "TIPOLOGY"
},
{
"id": "XXXX",
"tipology": "TIPOLOGY"
}
],
"num": 2
}
OR
{
"sections": [{
"id": "XXXX",
"tipology": "TIPOLOGY"
},
{
"id": "XXXX",
"tipology": "TIPOLOGY"
}, {
"id": "COUNT",
"num": 2
}
]
}
You can have the json object in the following format, hope it works for you.
{
"sections": {
"num": 100,
"values": [{
"id": "XXXX",
"tipology": "TIPOLOGY"
}]
}
}
And the java code for the above program is below.
import org.json.*;
class test {
public static void main(String[] args) throws JSONException {
JSONObject sections = new JSONObject();
JSONObject obj = new JSONObject();
obj.put("num", new Integer(2));
JSONArray array = new JSONArray();
JSONObject value = new JSONObject();
value.put("id", "XXXX");
value.put("tipology", "TIPOLOGY");
array.put(value);
obj.put("values", array);
sections.put("sections", obj);
System.out.print(sections);
}
}
Related
I'm having an issue comparing two json because some times the json that I recive from DB is oldEncodedString has values unordered
private static boolean encodeProduct(BaseProduct baseProduct) {
boolean saveProduct = false;
try {
saveProduct = true;
String oldEncodedString = baseProduct.getEncodedJson();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true);
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
String json = objectMapper.writeValueAsString(baseProduct);
Objects.requireNonNull(baseProduct).setEncodedJson(json);
if (Objects.nonNull(oldEncodedString) && JSONCompare.compareJSON(oldEncodedString, baseProduct.getEncodedJson(), JSONCompareMode.STRICT).passed()) {
saveProduct = false;
}
} catch (Exception exception) {
LOG.error("Error generating encode", exception);
}
return saveProduct;
}
eg:
oldEncodedString = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1003", "type": "Blueberry" },
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1004", "type": "Devil's Food" }
]
}}
baseProduct.getEncodedJson =
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
}}
So the values are unordered and when I compare into that if with STRICT is said that is not the same , but because is not ordered the values I tryed adding ObjectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true)
but is not on this library
Now i take JsonObject from API like this:
Its XML object converted to JsonObject.
"Details": {
"row": [
{
"item": [
{
"name": "Account",
"value": 12521512
},
{
"name": "ACCNO",
"value": 4214
},
{
"name": "Number",
"value": 5436
}
]
},
"item": [
{
"name": "Account",
"value": 5789678
},
{
"name": "ACCNO",
"value": 6654
},
{
"name": "Number",
"value": 0675
}
]
},
But i need convert this object and send like this:
{
"Details": {
"row": [
{
"Account": 12521512,
"ACCNO": 4214,
"Number": 12412421
},
{
"Account": 5789678,
"ACCNO": 6654,
"Number": "0675"
}
]
}
}
I have rows more than 1000, i need faster way to handle.
How to handle, please help me
You could use the JSON-java library to parse your input and transform it to your desired format. Something like this works but you may need to adjust it to your needs:
JSONObject jsonObject = new JSONObject(json); // Load your json here
JSONObject result = new JSONObject("{\"Details\": {\"row\": []}}");
for (Object row : jsonObject.getJSONObject("Details").getJSONArray("row")) {
if (!(row instanceof JSONObject)) continue;
Map<Object, Object> values = new HashMap<>();
for (Object item : ((JSONObject) row).getJSONArray("item")) {
if (!(item instanceof JSONObject)) continue;
values.put(((JSONObject) item).get("name"), ((JSONObject) item).get("value"));
}
result.getJSONObject("Details").getJSONArray("row").put(values);
}
// Now result is in your format
I am trying to get a JSON object nested inside another JSON object. When I run my main class:
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, JSONException {
NBAPlayers players = new NBAPlayers();
JSONObject json = players.readJsonFromUrl("http://data.nba.net/10s/prod/v1/2017/players.json");
JSONObject League = json.getJSONObject("league");
JSONObject standard =League.getJSONObject("standard");
JSONObject firstName = standard.getJSONObject("firstName");
}
}
I get the error:
Exception in thread "main" org.json.JSONException:
JSONObject["standard"] is not a JSONObject.
I am using the the maven artifact org.json:json package.
This is a part of json that returns url in the example
{
"_internal": {
"pubDateTime": "2017-12-10 11:42:23.504",
"xslt": "xsl/league/roster/marty_active_players.xsl",
"eventName": "league_roster"
},
"league": {
"standard": [
{
"firstName": "Alex",
"lastName": "Abrines",
"personId": "203518",
"teamId": "1610612760",
"jersey": "8",
"isActive": true,
"pos": "G",
"heightFeet": "6",
"heightInches": "6",
"heightMeters": "1.98",
"weightPounds": "190",
"weightKilograms": "86.2",
"dateOfBirthUTC": "1993-08-01",
"teams": [
{
"teamId": "1610612760",
"seasonStart": "2016",
"seasonEnd": "2017"
}
],
"draft": {
"teamId": "1610612760",
"pickNum": "32",
"roundNum": "2",
"seasonYear": "2013"
},
"nbaDebutYear": "2016",
"yearsPro": "1",
"collegeName": "",
"lastAffiliation": "Spain/Spain",
"country": "Spain"
},
{
"firstName": "Quincy",
"lastName": "Acy",
"personId": "203112",
"teamId": "1610612751",
"jersey": "13",
"isActive": true,
"pos": "F",
"heightFeet": "6",
"heightInches": "7",
"heightMeters": "2.01",
"weightPounds": "240",
"weightKilograms": "108.9",
"dateOfBirthUTC": "1990-10-06",
"teams": [
{
"teamId": "1610612761",
"seasonStart": "2012",
"seasonEnd": "2013"
},
{
"teamId": "1610612758",
"seasonStart": "2013",
"seasonEnd": "2013"
},
{
"teamId": "1610612752",
"seasonStart": "2014",
"seasonEnd": "2014"
},
{
"teamId": "1610612758",
"seasonStart": "2015",
"seasonEnd": "2015"
},
{
"teamId": "1610612742",
"seasonStart": "2016",
"seasonEnd": "2016"
},
{
"teamId": "1610612751",
"seasonStart": "2016",
"seasonEnd": "2017"
}
],
as you can see standard is not an object. It is array.
You should change your code as follows
JSONArray standard =League.getJSONArray("standard");
for (int i = 0; i < standard.length(); i++) {
String firstName = standard.getJSONObject(i).getString("firstName");
}
I want to parse this json in android. Can you help me how to parse, if i need to start from head to parse or from results for this I don't know. Can you help me
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}
Okay, first of all the JSON string you've given is invalid. I've written my answer based on the correct version of the JSON string that you have provided
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}
Now, to get the "values", you'll need to do this.
JSONObject jsonObject = new JSONObject(response);
JSONObject results = jsonObject.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
for (int i = 0; i < bindings.length(); i++) {
JSONObject binding = bindings.getJSONObject(i);
JSONObject city = binding.getJSONObject("city");
// Get value in city
String cityValue = city.getString("value");
Log.d("CITY", cityValue);
JSONObject country = binding.getJSONObject("country");
// Get value in country
String countryValue = country.getString("value");
Log.d("COUNTRY", countryValue);
}
How can I parse this piece of JSON code?
{
"direction": "ltr",
"id": "feed/http => //www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"continuation": "CLKM0OyU0rYC",
"self": [
{
" href": "https => //cloud.feedly.com/reader/3/stream/contents/feed%2Fhttp%3A%2F%2Fwww.theverge.com%2Frss%2Ffull.xml?n=20&unreadOnly=true"
}
],
"alternate": [
{
"href": "http://www.theverge.com/",
"type": "text/html"
}
],
"updated": 1367539068016,
"items": [
{
"id": "entryId",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "NBC's reviled sci-fi drama 'Heroes' may get a second lease on life as Xbox Live exclusive",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236096/nbc-heroes-may-get-a-second-lease-on-life-on-xbox-live",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "..."
},
"author": "Nathan Ingraham",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 15
},
{
"id": "entryId2",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "Senate rejects bipartisan gun control measure for background checks despite broad public support",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236136/senate-rejects-gun-control-amendment",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "...html content..."
},
"author": "T.C. Sottek",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 39
}
]
}
That is my solution but it doesn't work... what is my error? thanks
try{
//JSONArray elements = new JSONArray (response);
JSONObject json=new JSONObject(response);
JSONArray elements = json.getJSONArray("items");
Log.d(TAG, "Elemenenti numero" +elements.length());
// Getting Array of Contacts
// looping through All Contacts
for(int i = 0; i < elements.length(); i++){
JSONObject c = elements.getJSONObject(i);
// Storing each json item in variable
String identifier = c.getString("id");
String title = c.getString("title");
String link = c.getString("originId");
String data = c.getString("published");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date=new Date();
try {
date = format.parse(data);
System.out.println(date);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
String summary = summaryObj.getString("content");
JSONObject contentObj= c.getJSONObject("content");
String content = contentObj.getString("content");
JSONObject sourceObj= c.getJSONObject("origin");
String source = contentObj.getString("title");
if (summary.length()==0 && content.length()!=0) summary=content;
if (content.length()==0 && summary.length()!=0) content=summary;
String image=this.getFirstImage(content);
FeedItem toAdd=new FeedItem(identifier, title, link, date, null, summary, content, image, source);
toAdd.toString();
}
}catch (JSONException e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
There is no element called summary, you may try
if(c.has("summary")) {
JSONObject summaryObj= c.getJSONObject("summary");
}
if that doesn't work, please post your stacktrace, (logcat)
You don't have any tag named "originID". but you are trying to get String from it.
Similarly,you don't have tag "summary" also but you are trying to get JSONObject from it.