How to make a JSON object ordered? - java

Java file to set and get the values. I have set the boId as the first:
if(etsBuildOrder != null){
buildOrder.setBoId(etsBuildOrder.getBoId());
buildOrder.setName(etsBuildOrder.getName());
buildOrder.setFactory(etsBuildOrder.getFactory());
buildOrder.setStatus(etsBuildOrder.getStatus());
buildOrder.setIssued(etsBuildOrder.getIssued());
buildOrder.setTeam(etsBuildOrder.getTeam());
buildOrder.setType(etsBuildOrder.getType());
buildOrder.setBuildId(etsBuildOrder.getBuildRequestId());
buildOrder.setPartNumber(etsBuildOrder.getPartNumber());
buildOrder.setProductCode(etsBuildOrder.getProductCode());
buildOrder.setSpecialInstructions(etsBuildOrder.getSpecialInstructions());
buildOrder.setBoCreationDate(RestWsUtil.convertDateToString(etsBuildOrder.getCreationDate(), Constants.SIMPLE_DATE_FORMAT_DATE_ONLY));
buildOrder.setBoModifiedDate(RestWsUtil.convertDateToString(etsBuildOrder.getModifiedDate(), Constants.SIMPLE_DATE_FORMAT_DATE_ONLY));
buildOrder.setChangeHistory(etsBuildOrder.getChangeHistory());
}
JSON return format. boId is not located at the beginning of JSON:
{
"name": "TLO9009",
"factory": "L-Slider",
"type": null,
"boCreationDate": "18 Apr 2018",
"boModifiedDate": "18 Apr 2018",
"status": "Pending Approval",
"team": null,
"partNumber": null,
"specialInstructions": "Special Inst",
"changeHistory": "Pending ApprovalWed Apr 18 10:14:06 SGT 2018",
"productCode": null,
"issued": null,
"multifeature": null,
"buildId": 0,
"boId": 141
}
How the JSON should return. I would like the JSON to return like this:
{
"boId": 141
"name": "TLO9009",
"factory": "L-Slider",
"type": null,
"boCreationDate": "18 Apr 2018",
"boModifiedDate": "18 Apr 2018",
"status": "Pending Approval",
"team": null,
"partNumber": null,
"specialInstructions": "Special Inst",
"changeHistory": "Pending ApprovalWed Apr 18 10:14:06 SGT 2018",
"productCode": null,
"issued": null,
"multifeature": null,
"buildId": 0
}
I am new to JAVA and help is much appreciated.Thanks in advance.

That is not possible and not necessary. Both JSON objects are identical, there is not order.
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
https://json.org/

Related

Parsing JSON response when returned as Array

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
This is the error I continue to get while attempting to parse my incoming JSON response data. I'm utilizing the OkHttp library to create and call, and the API I'm getting results from returns everything in an Array as follows:
[
{
"id": 4256,
"image_url": "https://cdn.pandascore.co/images/league/image/4256/OMEN_Challenger_Series_2019.png",
"live_supported": false,
"modified_at": "2019-10-30T10:02:42Z",
"name": "OMEN Challenger",
"series": [
{
"begin_at": "2019-11-01T03:30:00Z",
"description": null,
"end_at": null,
"full_name": "2019",
"id": 1932,
"league_id": 4256,
"modified_at": "2019-10-30T09:11:40Z",
"name": null,
"prizepool": "50000 United States Dollar",
"season": null,
"slug": "cs-go-omen-challenger-2019",
"winner_id": null,
"winner_type": null,
"year": 2019
}
],
"slug": "cs-go-omen-challenger",
"url": "https://omengaming.co/omen_cs/",
"videogame": {
"current_version": null,
"id": 3,
"name": "CS:GO",
"slug": "cs-go"
}
},
{...},
{...},
{...},
{...},
]
I found a lot of folks recommending Gson to parse it into a custom class, but the following code, in theory, should work and it isn't. The parsing doesn't even begin due to it expecting BEGIN_OBJECT and it being BEGIN_ARRAY:
String jsonData = response.body().string();
Gson gson = new Gson();
EventInfo test = gson.fromJson(jsonData, EventInfo.class);
class EventInfo {
String imageURL;
String name;
JSONArray series;
}
You are trying to parse it into an object. But in your response, you can clearly see that it's a list. The parent POJO should have been a list. And inside that list, you should have created another POJO.
In your response parent is found as array but you need to add first parent as JSON object and child as a array or object.
You need response like this
{
"YourArrayName":[
"YourChildObjName":{
"id": 4256,
"image_url": "https://cdn.pandascore.co/images/league/image/4256/OMEN_Challenger_Series_2019.png",
"live_supported": false,
"modified_at": "2019-10-30T10:02:42Z",
"name": "OMEN Challenger",
"series": [
{
"begin_at": "2019-11-01T03:30:00Z",
"description": null,
"end_at": null,
"full_name": "2019",
"id": 1932,
"league_id": 4256,
"modified_at": "2019-10-30T09:11:40Z",
"name": null,
"prizepool": "50000 United States Dollar",
"season": null,
"slug": "cs-go-omen-challenger-2019",
"winner_id": null,
"winner_type": null,
"year": 2019
}
],
"slug": "cs-go-omen-challenger",
"url": "https://omengaming.co/omen_cs/",
"videogame": {
"current_version": null,
"id": 3,
"name": "CS:GO",
"slug": "cs-go"
}
},
{...},
{...},
{...},
{...},
]
}
I hope this can help You!
Thank You
So, I figured it out. Originally I was receiving the same error at a later point; namely when it got to the series key value in the first JSONObject. The original error occurred because I was trying to parse series as a JSONArray, rather than a List<JSONObject> The corrections are below:
String jsonData = response.body().string();
Gson gson = new Gson();
Type listType = new TypeToken<List<EventInfo>>() {}.getType();
List<EventInfo> test = gson.fromJson(jsonData, listType);
And the EventInfo class:
class EventInfo {
String imageURL;
String name;
List<JSONObject> series;
}
Thank you for the advice everyone!

Getting Last 4 Digits of Card using Customer Object - Stripe API

I am using Stripe API and using below code I fetch details -
Customer cu = Customer.retrieve(customerid); // customerid
List<ExternalAccount> object = cu.getSources().getData();
Log.d("customerobj",object + "");
I get this object data
D/customerobj: [
<com.stripe.model.Card#148232829id=>JSON: {
"address_city": null,
"address_country": null,
"address_line1": null,
"address_line1_check": null,
"address_line2": null,
"address_state": null,
"address_zip": "71000",
"address_zip_check": "pass",
"available_payout_methods": null,
"brand": "Visa",
"country": "US",
"currency": null,
"cvc_check": "pass",
"default_for_currency": null,
"description": null,
"dynamic_last4": null,
"exp_month": 4,
"exp_year": 2021,
"fingerprint": "EmNhHLSbWLElhMvG",
"funding": "credit",
"iin": null,
"issuer": null,
"last4": "4242",
"name": null,
"recipient": null,
"status": null,
"three_d_secure": null,
"tokenization_method": null,
"type": null,
"account": null,
"customer": "cus_DL2GSWX9bfTZeU",
"id": "card_1CuMC8A41bIzZYFFlpiW3hZp",
"metadata": {
},
"object": "card"
}
]
I want to get last 4 digits card number, exp_year, exp_month and address_zip.
Please help me get this String values
To get a specific key you can do:
object.get(index)
For exp_month, you would do object.get(16), for exp_year, you would do object.get(17) and for last4 you would do object.get(22)

how to split 1GB JSON file into multiple JSON object file each

I have a JSON file of size 1GB which contains n number of twitter JSON Object tweets.Now I want to split large JSON file into single JSON Object each. But in large file the JSON chunks are space separated but not comma separated.
INPUT :-
{
"created_at": "Tue Aug 06 06:01:00 +0000 2013",
"id": 364627145785487360,
"id_str": "364627145785487360",
"text": "Soo sad right now..",
"filter_level": "medium",
"lang": "en"
}
{
"created_at": "Tue Aug 06 06:01:00 +0000 2013",
"id": 364627145785487360,
"id_str": "364627145785487361",
"text": "الضمير صوت هادىء يخبرك بأن احدا ينظر اليك",
"lang": "en"
}
Now my OUTPUT has to be as shown below
OUTPUT: Test1.json
{
"created_at": "Tue Aug 06 06:01:00 +0000 2013",
"id": 364627145785487360,
"id_str": "364627145785487360",
"text": "Soo sad right now..",
"filter_level": "medium",
"lang": "en"
}
Test2.json
{
"created_at": "Tue Aug 06 06:01:00 +0000 2013",
"id": 364627145785487360,
"id_str": "364627145785487361",
"text": "الضمير صوت هادىء يخبرك بأن احدا ينظر اليك",
"lang": "en"
}
Can anyone help me out to get the above output JSON files i.e, Test1.json, Test2.json
given number of lines (7000 in this case):
command : jq -c -M '.data[]' | split -l 7000

access elementsJSON array in Java

I am new to JSON. I know the forecast is an array, but how do I access elements date and text? I know where the problem is: It seems i cannot get access to forecast array, as this gives a null.
JSONArray jArr = data.getJSONArray("forecast");
what is the proper notation to get access to the forecast array. I was trying
`JSONArray jArr = data.getJSONObject("item").getJSONObject("condition").getJSONArray("forecast");
but this notation still did not give me access to the array. What notation will give me correct reference to forecast array?
"item": {
"title": "Conditions for Kingston, Saint Andrew, JM at 09:00 PM EST",
"lat": "18.015711",
"long": "-76.79731",
"link": "http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https://weather.yahoo.com/country/state/city-109251/",
"pubDate": "Sat, 22 Oct 2016 09:00 PM EST",
"condition": {
"code": "27",
"date": "Sat, 22 Oct 2016 09:00 PM EST",
"temp": "77",
"text": "Mostly Cloudy"
},
"forecast": [
{
"code": "32",
"date": "20 Oct 2016",
"day": "Thu",
"high": "35",
"low": "26",
"text": "Sunny"
},
{
"code": "34",
"date": "21 Oct 2016",
"day": "Fri",
"high": "34",
"low": "28",
"text": "Mostly Sunny"
},
{
"code": "26",
"date": "22 Oct 2016",
"day": "Sat",
"high": "37",
"low": "32",
"text": "Cloudy"
},
{
"code": "23",
"date": "23 Oct 2016",
"day": "Sun",
"high": "37",
"low": "34",
"text": "Breezy"
},
I was trying something like this, but my android app was crashing? I just need help in accessing the elements in the array to set them on some textfields.
public void populate(JSONObject data) throws JSONException {
JSONArray jArr = data.getJSONArray("forecast");
for(int i=0;i<jArr.length();i++){
JSONObject jDayForecast = jArr.getJSONObject(i);
String date = jDayForecast.getString("date");
String text = jDayForecast.getString("text");
}
}
here is the error in stacktrace.
54.516 27220-27220/net.digitalphantom.app.weatherapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.digitalphantom.app.weatherapp, PID: 27220
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String net.JamCast.app.weatherapp.data.Forecast.getDate()' on a null object reference
at net.JamCast.app.weatherapp.WeatherActivity$override.serviceSuccess(WeatherActivity.java:363)
at net.JamCast.app.weatherapp.WeatherActivity$override.access$dispatch(WeatherActivity.java)
at net.JamCast.app.weatherapp.WeatherActivity.serviceSuccess(WeatherActivity.java:0)
at net.JamCast.app.weatherapp.service.YahooWeatherService$1.onPostExecute(YahooWeatherService.java:95)
at net.JamCast.app.weatherapp.service.YahooWeatherService$1.onPostExecute(YahooWeatherService.java:37)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
define a java bean class, use GSON jar translate json string to class object, then you can get text element by your object. please search in google sample.

Regex to remove ID numbers

I have a large text file and am looking for a regex to be able to remove all id numbers between 8-10 characters and save them as comma separated.
One row of the file is as follows:
{"follow_request_sent": null, "profile_use_background_image": true, "id": 340671834, "description": "This is The Official Fans Page Of One Direction! We will update you with the latest news 24/7! Follow https://t.co/ZJLh8usZ80 and follow #itsdirectlieber", "verified": false, "profile_image_url_https": "https://si0.twimg.com/profile_images/3057650709/cc214d87e8b65324677f3a99bdff3bd4_normal.jpeg", "profile_sidebar_fill_color": "E8EAEB", "profile_text_color": "949494", "followers_count": 353767, "protected": false, "location": "Brazil", "default_profile_image": false, "id_str": "340671834", "status": {"favorited": false, "contributors": null, "truncated": false, "text": "Ill make a test now, bye.", "created_at": "Fri Apr 12 11:27:01 +0000 2013", "retweeted": false, "in_reply_to_status_id": null, "coordinates": null, "id": 322672198861090816, "source": "Twitter for Android", "in_reply_to_status_id_str": null, "place": null, "id_str": "322672198861090816", "in_reply_to_screen_name": null, "retweet_count": 10, "geo": null, "in_reply_to_user_id_str": null, "in_reply_to_user_id": null}, "utc_offset": -10800, "statuses_count": 22301, "profile_background_color": "FFFFFF", "friends_count": 60311, "profile_background_image_url_https": "https://si0.twimg.com/profile_background_images/837595304/7352cbbc52911b16816807c7fc39824d.png", "profile_link_color": "E80C38", "profile_image_url": "http://a0.twimg.com/profile_images/3057650709/cc214d87e8b65324677f3a99bdff3bd4_normal.jpeg", "notifications": null, "geo_enabled": false, "profile_banner_url": "https://si0.twimg.com/profile_banners/340671834/1365451996", "profile_background_image_url": "http://a0.twimg.com/profile_background_images/837595304/7352cbbc52911b16816807c7fc39824d.png", "name": "One Direction", "lang": "en", "following": null, "profile_background_tile": false, "favourites_count": 301, "screen_name": "1DFAMlLY", "url": "http://www.facebook.com/1DFAMlLY", "created_at": "Sat Jul 23 02:36:18 +0000 2011", "contributors_enabled": false, "time_zone": "Brasilia", "profile_sidebar_border_color": "FFFFFF", "default_profile": false, "is_translator": false, "listed_count": 1317}
I am trying to remove the id and save it as a seperate comma seperated string
Any help greatly appreciated.
You can use the {N,M} operator to define ranges of characters in regular expressions. For example, \\d{8,10} can be used to find numbers between 8-10 characters.
In order to find all ids you use the following regular expression:
String input = "your string here";
Pattern pattern = Pattern.compile("\"id\":\\s*(\\d{8,10})\\s*[,}]");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
You should however consider using a JSON parser. It is far more suitable for this work and will probably save you some headaches in the future.

Categories