How to parse JSON in Java

I have the following JSON text. How can I parse it to get pageName, pagePic, post_id, etc.?

{
   "pageInfo": {
         "pageName": "abc",
         "pagePic": "http://example.com/content.jpg"
    }
    "posts": [
         {
              "post_id": "123456789012_123456789012",
              "actor_id": "1234567890",
              "picOfPersonWhoPosted": "http://example.com/photo.jpg",
              "nameOfPersonWhoPosted": "Jane Doe",
              "message": "Sounds cool. Can't wait to see it!",
              "likesCount": "2",
              "comments": [],
              "timeOfPost": "1234567890"
         }
    ]
}

How to parse JSON without JSON.NET library?

I’m trying to build a Metro application for Windows 8 on Visual Studio 2011.
and while I’m trying to do that, I’m having some issues on how to parse JSON without JSON.NET library (It doesn’t support the metro applications yet).

Anyway, I want to parse this:

{
   "name":"Prince Charming",
   "artist":"Metallica",
   "genre":"Rock and Metal",
   "album":"Reload",
   "album_image":"http:\/\/up203.siz.co.il\/up2\/u2zzzw4mjayz.png",
   "link":"http:\/\/f2h.co.il\/7779182246886"
}

JSON Self referencing loop

I’m building some small booking app and I’m getting this error all the time.

I solved it with:
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

but now I’m getting answer like this:

{
    "ApartmentId": 1,
    "Building": {
        "BuildingId": 1,
        "Apartments": [
            {
                "ApartmentId": 2,
            }
        ]
    },
}

For class building everything works fine. It’s only going “to far” for the apartment. I tried solutions from this topic but it didn’t work: https://stackoverflow.com/questions/7397207/json-net-error-self-referencing-loop-detected-for-type#=

Here are my classes:

public class Apartment
{
    public int ApartmentId { get; set; }
    public Building Building { get; set; }
}

public class Building
{
    public int BuildingId { get; set; }
    public List<Apartment> Apartments { get; set; }
}

The question is, what am I missing? How to get rid of listing of apartments for the second time?

Gson – Exception while deserializing object

I have the following object that I am trying to use Gson to serialize/deserialize:

public class ReportTemplate {

    private SimpleStringProperty templateName = new SimpleStringProperty("");
    private SimpleObjectProperty<ReportTemplate> destinationTemplate = new SimpleObjectProperty<>();

    // The list of ReportColumns; holds the format as well
    private ArrayList<ReportColumn> columns;

    public ReportTemplate() {
    }

    public ReportTemplate(ArrayList<ReportColumn> columns) {
        this.columns = columns;
    }

    public String getTemplateName() {
        return templateName.get();
    }

    public SimpleStringProperty templateNameProperty() {
        return templateName;
    }

    public void setTemplateName(String templateName) {
        this.templateName.set(templateName);
    }

    public ReportTemplate getDestinationTemplate() {
        return destinationTemplate.get();
    }

    public SimpleObjectProperty<ReportTemplate> destinationTemplateProperty() {
        return destinationTemplate;
    }

    public void setDestinationTemplate(ReportTemplate destinationTemplate) {
        this.destinationTemplate.set(destinationTemplate);
    }

    public List<ReportColumn> getColumns() {
        return columns;
    }

    public void setColumns(ArrayList<ReportColumn> columns) {
        this.columns = columns;
    }

    public ReportColumn getReportColumn(int index) {
        return columns.get(index);
    }

    @Override
    public String toString() {
        return templateName.get();
    }
}

Running the following test code works perfectly fine:

class Test {

    private static ReportTemplate destinationFormat;
    private static ReportTemplate sourceFormat;
    private static HashMap<Integer, Integer> mappedColumns;

    public static void main(String[] args) {

        // Template Lists
        ArrayList<ReportTemplate> sources = new ArrayList<>();
        ArrayList<ReportTemplate> dests = new ArrayList<>();

        ReportTemplate hiscox = new ReportTemplate(getSource());
        hiscox.setTemplateName("Hiscox");

        ReportTemplate agm = new ReportTemplate(getDestination());
        agm.setTemplateName("Monthly AGM");

        hiscox.setDestinationTemplate(agm);
        dests.add(agm);
        sources.add(hiscox);

        Global.setSourceTemplates(sources);
        Global.setDestinationTemplates(dests);

        TemplatesDatasource.saveTemplates(Global.getSourceTemplates());
        TemplatesDatasource.saveTemplates(Global.getDestinationTemplates());

        TemplatesDatasource.loadTemplates();

    }

    private static ArrayList<ReportColumn> getSource() {
        // Hiscox source format
        ArrayList<ReportColumn> sourceColumns = new ArrayList<>();
        sourceColumns.add(new ReportColumn("Policy No.", 0, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Event Type", 1, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("New or Renewal", 2, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Insured Name", 3, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Display Date", 4, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Processed Date", 5, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Policy Effective Date", 6, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Policy Expiration Date", 7, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Premium", 8, ColumnFormat.CURRENCY));
        sourceColumns.add(new ReportColumn("Commission Rate", 9, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Commission", 10, ColumnFormat.CURRENCY));
        sourceColumns.add(new ReportColumn("State", 11, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Partner", 12, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Partner Agent Name", 13, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Partner Agency Name", 14, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Partner Agent", 15, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Partner Agency Phone Number", 16, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Partner Agent Email", 17, ColumnFormat.TEXT));
        sourceColumns.add(new ReportColumn("Partner Agent Representative", 18, ColumnFormat.TEXT));
        return sourceColumns;
    }

    private static ArrayList<ReportColumn> getDestination() {
        // Destination format
        ArrayList<ReportColumn> destinationColumns = new ArrayList<>();
        destinationColumns.add(new ReportColumn("Agent Code", 0, ColumnFormat.TEXT));
        destinationColumns.add(new ReportColumn("Agent Name", 1, ColumnFormat.TEXT));
        destinationColumns.add(new ReportColumn("Agent Zip Code", 2, ColumnFormat.TEXT));
        destinationColumns.add(new ReportColumn("Agent Email Address", 3, ColumnFormat.TEXT));
        destinationColumns.add(new ReportColumn("Line of Business", 4, ColumnFormat.TEXT));
        destinationColumns.add(new ReportColumn("Policy Number", 5, ColumnFormat.TEXT));
        destinationColumns.add(new ReportColumn("Event Type", 6, ColumnFormat.TEXT));
        destinationColumns.add(new ReportColumn("Insured Name", 7, ColumnFormat.TEXT));
        destinationColumns.add(new ReportColumn("Premium", 8, ColumnFormat.CURRENCY));
        destinationColumns.add(new ReportColumn("Effective Date", 9, ColumnFormat.TEXT));
        return destinationColumns;
    }
}

Now, in my actual application, I use the ReportTemplate objects to populate various JavaFX controls (by converting them to ObservableArrayList when running the setItems() method; I do not alter the original list in any way.

When serializing the ReportTemplate objects back to JSON in my application, the output includes “helper” and “observable” keys. When trying to load those output files again, I get the following two exceptions:

java.lang.UnsupportedOperationException: Abstract class can't be instantiated! Class name: com.sun.javafx.binding.ExpressionHelper
java.lang.RuntimeException: Unable to invoke no-args constructor for com.sun.javafx.binding.ExpressionHelper<java.lang.String>. Registering an InstanceCreator with Gson for this type may fix this problem.

Here is the code I use to save them from my application (which is identical to the above):

// save the Templates
        TemplatesDatasource.saveTemplates(Global.getSourceTemplates());
        TemplatesDatasource.saveTemplates(Global.getDestinationTemplates());

Within Global, the original source and destination template lists are not altered in any way after creating them with the fromJson() method in Gson.

I have spent several hours looking up various similar questions, but none seem to address why Gson is including extra keys in the output Json when it should be identical to the test output.

Could someone please suggest where my problem may lie? I have been unable to duplicate the error in a smaller test project, so it obviously has something to do with my complete application, whose code is too large to post here.

Laravel 4.2 getting error array_merge(): Argument #2 is not an array

I am having a trouble with my project, It shows the error array_merge(): Argument #2 i have tried using composer update but the update do not work because it shows the same error in the console, i don’t know what cause the problem, i have not touched it and anyone else should be working on it, so if any help would be thankfull.

im using laravel 4.2 this is the error stack

6. ErrorException
…/­vendor/­laravel/­framework/­src/­Illuminate/­Foundation/­ProviderRepository.php188
5. Illuminate\Exception\Handler handleError
<#unknown>0
4. array_merge
…/­vendor/­laravel/­framework/­src/­Illuminate/­Foundation/­ProviderRepository.php188
3. Illuminate\Foundation\ProviderRepository loadManifest
…/­vendor/­laravel/­framework/­src/­Illuminate/­Foundation/­ProviderRepository.php50
2. Illuminate\Foundation\ProviderRepository load
…/­vendor/­laravel/­framework/­src/­Illuminate/­Foundation/­start.php210
1. require
…/­bootstrap/­start.php60
0. require_once
/­home/­{myproject}/­public_html/

The error does not come from a code i write myself, but from the core of laravel in /­vendor/­laravel/­framework/­src/­Illuminate/­Foundation/­ProviderRepository.php188 i have read that the service.json file maybe corrupted, i have deleted it and try to run composer update but the error persist and the update does not run

Swifty Json parsing

I am using SwiftyJson library for parsing my following json

{
    "data": {
        "id": "12345",
        "messages": {
            "message": "{\"data\":{\"msg\":\"HelloMsg\"}}"
        }
    }
}

I tried to use following code to get msg parameter

let json = JSON(data)
let msg = JSON(json["data"]["messages"]["message"])
msg["data"]["msg"].stringValue

However, I could not get the value of msg parameter. What shall I do to get HelloMsg?

Deserializing JSON in Java what contains nested object holding generic Type

I have a JSON like below :

    {
"Entities": [
    {
        "Name": "person",
        "Id": "2425353484387437663",
        "ExtraInfo": [
            {
                "Key": "customertypecode",
                "Value": {
                    "Value": 712340000,
                    "ExtendedInfo": {}
                }
    },
            {
                "Key": "address2_addresstypecode",
                "Value": {
                    "Value": 1,
                    "ExtendedInfo": {}
                }
    },
            {
                "Key": "merged",
                "Value": false
    },
            {
                "Key": "gendercode",
                "Value": {
                    "Value": 1,
                    "ExtendedInfo": {}
                }
    }]
    }]
    }

And I can’t find any tip about something similar to it.
I saw instructions giving tips about how to deserialize JSON when “the main” structure is of a generic Type.

How to specify each type of such nested object in any of existing library for JSON deserializing?

Android does not Toast after successful POST

I am sending data from an android client to a grails backend. I want two things to happen when data is successfully posted:

  1. A toast with some of the params I have posted(In this case I want
    only name)
  2. An intent to open another activity.

However with my code, the parameters are posted successfully to the db but the toast and the intent do not happen.

Here is my code:

 */
    private void registerUser(final String chname, final String chdesc, final String patientID) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Registering ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                Configs.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");
                    if (!error) {
                        // User successfully stored in MySQL
                        // Now store the user in sqlite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String chname = user.getString("name");
                        String chdesc = user.getString("description");
                        String patientID = user.getString("patient");



                        Toast.makeText(getApplicationContext(), "User successfully registered.", Toast.LENGTH_LONG).show();

                        // Launch login activity
                        Intent intent = new Intent(AddChronics.this,
                                ChronicsFragment.class);
                        startActivity(intent);
                        finish();
                    } else {

                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Registration Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to activity_register url
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", chname);
                params.put("description", chdesc);
                params.put("patient", patientID);

                params.put("action", "chronicAdd");

                return params;


            }


        };



        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

Note: The API works just fine. I have checked and the params are successfully saved to the db.

How to iterate an array of objects and only get specific values

I have an array of below format

[{
    "_id" : "500",
    "loanRef" : "500",
    "createdTime" : "2018-02-15T17:20:47.156Z",
    "bdetails" : {
        "config" : {
            "chase" : [
                6,
                12
            ],
            "expiry" : 35
        }
    },
},
{
    "_id" : "500",
    "loanRef" : "500",
    "createdTime" : "2018-02-15T18:11:45.377Z",
    "bdetails" : {
        "config" : {
            "chase" : [
                6,
                12
            ],
            "expiry" : 35
        }
    },
}
}]

The above array size is around 200..

But I want this in this format

[{
    "_id" : "500",
    "loanRef" : "500",
    "createdTime" : "2018-02-15T17:20:47.156Z",
    "chase" : "[6,12]",
    "expiry" : 35           
},
{
    "_id" : "500",
    "loanRef" : "500",
    "createdTime" : "2018-02-15T18:11:45.377Z",
    "chase" : "[6,12]",
    "expiry" : 35
}]

Can someone help how we can form this with some js logic..Any help would save me with this.Thanks

Get Column Names Of JSON String

I got this problem when i was trying to get Column list from a JSON String .
Im getting JSON String with ajax :

   var jsonData =   $.ajax({
                           method: "GET",
                           url: "read.jsp",
                           data: {title: option},
                           dataType: "json",
                           async: false
                           }).responseText; 

I choose a JSON file from a list and i get it

and I tried to Get column names with this :

var newData= JSON.parse(jsonData).["0"];
for(var i = 0; i < newData.length; i++) { 
        var columnsIn = newData[i]; 
        for(var key in columnsIn){ 
        alert(key); 
        } 
    }

The problem is with : [“0”] , when i replace it with the name of the first attribut , it works.

PS: Json file is not the same.

And this is an exemple of A json file :

{
"ASSETMboSet": {
    "rsStart": 0,
    "rsCount": 10,
    "rsTotal": 1262,
    "ASSET": [
        {
            "rowstamp": "[0 0 0 0 2 -100 91 -13]",
            "Attributes": {
                "ASSETNUM": {
                    "content": "1000"
                },
                "SERIALNUM": {
                    "content": "12346"
                },
                "VENDOR": {
                    "content": "1001"
                },
                "MANUFACTURER": {
                    "content": "1001"
                },
                "PURCHASEPRICE": {
                    "content": 0
                },
                "REPLACECOST": {
                    "content": 0
                }, .....

And this is an other exemple because its not the same json file i want to get column names from it :{<br /> "executionTime": "2018-02-16 05:49:04 AM",<br /> "stationBeanList": [<br /> {<br /> "id": 72,<br /> "stationName": "W 52 St & 11 Ave",<br /> "availableDocks": 31,<br /> "totalDocks": 39,<br /> "latitude": 40.76727216,<br /> "longitude": -73.99392888<br /> },<br /> {<br /> "id": 79,<br /> "stationName": "Franklin St & W Broadway",<br /> "availableDocks": 19,<br /> "totalDocks": 33,<br /> "latitude": 40.71911552,<br /> "longitude": -74.00666661}