Affichage des articles dont le libellé est Active questions tagged json - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged json - Stack Overflow. Afficher tous les articles

dimanche 28 juin 2015

how to run simple ODATA query dynamically and return result in json format using with Roslyn?

I'm working on query builder for simple Odata

I'm generating simple odata queries dynamically and want to show result of queries on json format.

query text:

   var DetailData = await myClient.For<CustomerDetail>().Filter(q => q.Id == id).OrderBy(q => q.Key).FindEntriesAsync();

how to run simple ODATA query dynamically and return result in json format?

Swift Haneke: Json Data in TextView

I used the Haneke Framework to get Data from a Site. With the Haneke Framework i also can get Images from a site, and these Images i can present on a UIImageView. Now i wanted to get some text from a site.

I did it like this:

 cache.fetch(URL: URL).onSuccess { JSON in
            println(JSON.dictionary?["index"])

It printed me all the data from "Index".

Now i want, that all the data from "Index" should be presented on a UITextView.

  self.textView.text = JSON.dictionary["index"]

But it doesn't work..

I get the error: Cannot assign a value of type 'AnyObject' to a value of type 'String!'

I have to unwrap it or?

How do I access the element title in the Json?

I want GET json from http://omadbapi.com/?s= for search script, but I'm having trouble with get Title elment in this JSON :

{
"Search": [
{
  "Title": "Sherlock Holmes: A Game of Shadows",
  "Year": "2011",
  "imdbID": "tt1515091",
  "Type": "movie"
},
{
  "Title": "Spy Kids 3-D: Game Over",
  "Year": "2003",
  "imdbID": "tt0338459",
  "Type": "movie"
}
]
}

JavaScript :

$(document).ready(function () {
    var url = 'http://www.omdbapi.com/?',
        mode = 's=',
        input,
        movieName;

    $('button').click(function() {
        var input = $('#movie').val(),
        movieName = encodeURI(input);

        $.getJSON( url + mode + input, function( data ) {

          $.each(data, function(e,p) {
            document.getElementById("item").innerHTML="Title : " + p.Title;
          });
    });
    });
});

p.Title or data.Title, I don't know...

"No matching records found" NOT displayed in "bootstrap-table"

I am using the "bootstrap-table" plugin for my website and currently using it's server side pagination properties.

The table is being populated correctly and the search feature also works. BUT when something not present is searched for it displays all the records instead of displaying "No matching records found".

This is the html code I am using...

<table data-toggle="table"
       data-url="1.php"
       data-pagination="true"
       data-side-pagination="server"
       data-page-list="[5, 10, 20, 50, 100, 200]"
       data-search="true"
       data-height="300">
    <thead>
    <tr>
        <th data-field="state" data-checkbox="true"></th>
        <th data-field="memberID" data-align="right" data-sortable="true">Member ID</th>
        <th data-field="name" data-align="center" data-sortable="true"> Name</th>
        <th data-field="dob" data-sortable="true">Date of Birth</th>
    </tr>
    </thead>


</table>

and this is the php script I am using to create the JSON response...

<?php

require_once('db-connect.php');

if(isset($_GET["limit"])) {
    $limit = $_GET["limit"];
} else {
    $limit = 10;
}

if(isset($_GET["offset"])) {
    $offset = $_GET["offset"];
} else {
    $offset = 0;
}

if(isset($_GET["sort"])) {
    $sort = $_GET["sort"];
} else {
    $sort = "";
}

if(isset($_GET["order"])) {
    $order = $_GET["order"];
} else {
    $order = "asc";
}

 if(isset($_GET["search"])) {
    $search = $_GET["search"];
 } else {
    $search = "";
 }


if($search == "") {
    $result = mysqli_query($connection,"select memberID, name, dob from memberdetails" );
} else {

    $result = mysqli_query($connection,"select memberID, name, dob from memberdetails WHERE memberID LIKE '%$search%'"  );
}


$row = array();

if ( mysqli_num_rows($result) > 0 ) {
            while($row = mysqli_fetch_assoc($result)) {
                $result_2d_arr[] = array (  'memberID' => $row['memberID'],
                                            'name' => $row['name'],
                                            'dob' => $row['dob']);
            }




//get the result size
$count = sizeof($result_2d_arr);

//order the array
if($order != "asc") {
    $result_2d_arr = array_reverse($result_2d_arr);
}

//get the subview of the array
$result_2d_arr = array_slice($result_2d_arr, $offset, $limit);



echo "{";
echo '"total": ' . $count . ',';
echo '"rows": ';
echo json_encode($result_2d_arr);
echo "}";

}

?>

The JSON response is as follows...

{"total": 23,"rows": [{"memberID":"1","name":"asd","dob":"2015-06-03"},{"memberID":"2","name":"asd","dob":"2015-06-03"},{"memberID":"3","name":"asd","dob":"2015-06-03"},{"memberID":"4","name":"asd","dob":"2015-06-03"},{"memberID":"5","name":"asd","dob":"2015-06-03"},{"memberID":"6","name":"asd","dob":"2015-06-03"},{"memberID":"7","name":"asd","dob":"2015-06-03"},{"memberID":"8","name":"asd","dob":"2015-06-03"},{"memberID":"9","name":"asd","dob":"2015-06-03"},{"memberID":"10","name":"asd","dob":"2015-06-03"}]}

Handle Post Data of JSON in PHP

I receive JSON post data ....

{"split_info":"17076370","customerName":"Lahoti","status":"failed","error_Message":"fail.","paymentId":"17076370","productInfo":"productInfo","customerEmail":"cxxxx.xx@gmail.com","customerPhone":"999999999","merchantTransactionId":"BR121","amount":"19.0","notificationId":"443"}

I have written PHP code to Update my Database using merchantTransactionId received as JSON post data. My database is not going to update... My php code is as below Please help..

<?php
include("dbconnection.php");
if(isset($_POST))
{
$json_a = json_decode($_POST, true);
 $Id=$json_a['merchantTransactionId'];
 $status="payUMoney";
 mysql_query("UPDATE std status= '".$payStatus."' WHERE Id='".$Id."'",$db);
?>

POST raw json code ios

i'm new to ios developing and i want to ask how can i post a raw json code to the server.

For Example: i want to send this JSON raw data to http://example.com/user

{ "user": 
                {   "username": "jkaaannyaad11",
                    "password": "secret123456",
                    "gender": "male",
                    "first_name": "assd",
                    "last_name": "ffsasd",
                    "birth_date": "can be null",
                    "phone_number": "12343234",
                                                                  "have_car":"1",
                                                                  "same_gender" :"0",
                                                                  "uid": "this is id for facebook , can be null"
                },
            "home": {
                    "longitude": "31.380301",
                    "latitude": "30.054272",
                    "name": "city"
                    },
            "work": {
                    "longitude": "30.068237",
                    "latitude": "31.024275",
                    "name": "village"
                    },
            "email": {
                    "email_type": "work",
                    "email": "hello.me@me.com"
                    }
            }

so how can i do it ?

Dearest Regards,

How can i parse json array?

I am building an Android app and i need to populate a custom listview with some data from my localhost. I am trying to use volley JsonArrayRequest to get that data under the format of a JSONObject array but all i get is org.json.JSONException: End of input at character 0 of. This is my json array request :

final String URL = "http://ift.tt/1TXdybA";
        JsonArrayRequest productsReq = new JsonArrayRequest(Method.POST, URL, new Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                Log.d("productTAG", response.toString());
                for(int i = 0; i < response.length(); i++)
                {
                    try 
                    {   
                        JSONObject productObj = response.getJSONObject(i);
                        String title = productObj.getString("title");
                        String description = productObj.getString("description");
                        String category = productObj.getString("category");
                        String subCategory = productObj.getString("subCategory");
                        String size = productObj.getString("size");
                        String price = productObj.getString("price");
                        String thumbnailUrl = productObj.getString("image_one");

                        Product product = new Product(title, thumbnailUrl, description, category, subCategory, size, price);
                        products.add(product);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }
        }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("products_error", error.getMessage().toString());
                error.printStackTrace();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                params.put("req", "products");
                params.put("category", category);
                params.put("subCategory", subCategory);

                return params;
            }
        };
        VolleyCore.getInstance(getActivity()).addToRequestQueue(productsReq); 

The method i am using is POST and under the getParams i am adding a tag named req which has the value products. I am checking for this tag in index.php. This is my function that queries the table:

public function getItems($category, $subCategory)
    {
        $query = mysql_query("SELECT * FROM items WHERE category = '$category' AND sub_category = '$subCategory'") or die(mysql_error());


        $objects = array();
        if($query)
        {
            while($objects = mysql_fetch_assoc($query))
            {
                $final[] = $objects;
            }
        }
        return $final;

    }

Here in index.php i am checking for the request:

if(isset($_POST['req']) && $_POST['req'] == 'products')
    {
        $category = $_POST['category'];
        $subCategory = $_POST['subCategory'];


        $obj = $func->getItems($category, $subCategory);

        echo json_encode($obj);

    }

$func is the instantiation of the class where i keep all the methods working with the database(including getItems()). If i use volley StringRequest i do get a response back, but then again why don't i get the response while using JsonArrayRequest ? What am i doing wrong?

Parsing json with gson and java

I am struggling to parse a json output with Java and gson, but I am really stuck.

I would appreciate any suugestion.

This is my sample JSON file:

{
"sportId": 29,
"last": 26142386,
"league": [
    {
        "id": 1833,
        "events": [
            {
                "id": 383911973,
                "starts": "2015-01-22T21:00:00Z",
                "home": "America de Natal",
                "away": "Barras",
                "rotNum": "901",
                "liveStatus": 0,
                "status": "O",
                "parlayRestriction": 0
            },
            {
                "id": 383911974,
                "starts": "2015-01-22T21:00:00Z",
                "home": "Baraunas RN",
                "away": "ASSU RN",
                "rotNum": "904",
                "liveStatus": 0,
                "status": "O",
                "parlayRestriction": 0
            }
        ]
    }
  ]
}

My target is to a make a 2-dimensional array (or something similar) of the form:

leagueId, eventId, home, away
------------------------------
   1         1       a    b
   .         .       .    .
   .         .       .    .
  etc       etc     etc   etc

in order to insert the data in a MYSQL table.

I have write the following classes:

public class Fixtures {
int last;
int sportId;
ArrayList<Leagues> league = new ArrayList<Leagues>();

public ArrayList<Leagues> getListOfLeagues() {  
    return league;  
}  

public int getSportId(){
    return sportId;
}

 public int getLast(){
    return last;
 }

}

public class Leagues {
int id;
ArrayList<Events> events;

public int getLeagueId(){
    return id;
}

 public ArrayList<Events> getListOfEvents() {  
    return events;  
 }  

}

public class Events {
int id;
String home;
String away;


public int getEventId(){
    return id;
}

public String getHome() {  
    return home;  
}  

 public String getAway() {
    return away;
 }


}

and

Gson gson = new GsonBuilder().create();             
Fixtures fixture = gson.fromJson(jsonsource, Fixtures.class);
System.out.println(fixture.getSportId());
System.out.println(fixture.getLast());

ArrayList<Leagues> Leagues = fixture.getListOfLeagues();

Dont know how to proceed :(

Mapping a large json object (from rest service) to a smaller object? LoDash?

I am receiving a list of tweets (from a rest service) which is a really big list of many properties but I am only interested in a few properties in each item in the collection that is returned.

What is the best way of mapping this to a smaller object?

Does lodash help here?

I do I just iterate over it and create many new object?

Any help appreciated.

How to store data of dynamically generated Forms on Submit in Android?

I am developing a android application in which I am creating different dynamic form controls of different forms from the JSON data at runtime. The form may contain EditText, Spinner, Chechboxlist, Radiobuttonlist or five Addressboxes of EditText. Each control may also appear multiple times in different order. Now, I have generated and displayed the form controls of different forms at runtime.

One Example Form :

TextBox1 : ___________

Spinner2 : Item1 Item2 Item3

TextBox3 : ___________

Checkbox4 :

  • Option1
  • Option2
  • Option3

Radiogroup5 :

  • Radio1
  • Radio2

Spinner6 : Item1 Item2

Checkbox7 :

  • Option1
  • Option2

Radiogroup8 :

  • Radio1
  • Radio2

Address9 : _____________ _____________ _____________ _____________ _____________

Here Address contains five EditText consecutively.Now other form may or may not contain this controls.Here TextBox1, Spinner2, TextBox3 etc are the unique label to identify the control. But my problem is to submit the data entered in the form. The form contains a submit button. By pressing it, I have to send POST JSON Request by form the JSON with the filled data.

Example JSON Request :

  { "FormData" : {
              {"Name":"TextBox1" , "Value":"DummyText"},
              {"Name":"Spinner2" , "Value":"Item3"},
              {"Name":"TextBox3" , "Value":"DummyText"},
              {"Name":"Checkbox4" , "Value":"Option2, Option3"},
              {"Name":"Radiogroup5" , "Value":"Radio2"},
              {"Name":"Spinner6" , "Value":"Item1"},
              {"Name":"Checkbox7" , "Value":"Option1"},
              {"Name":"Radiogroup8" , "Value":"Radio1"},
              {"Name":"Address9" , "Value":"Dummy1, Dummy2, Dummy3, Dummy4,Dummy5"} 



           }

So how to write the proper single code for storing and submitting that data for a particular dynamic form in a data structure in such a way that I can form that JSON Request? Thanks in advance.

Laravel 5 how to return a template with response()->json()?

Below is my database:

post:
id user_name content created_at

Below is my post controller:

public function new(Request $request){
        $data = $request->all();
        $post = new Post;
        $post->user_name = $data['name'];
        $post->message = $data['content'];
        $post->save();
        $id = $post->id;
        $show = Post::find($id)->first();
        // $html = view('wall.post')->with('post', $show);
        return response()->json(['success' => $post->id,'message'=> 'Post Sent', 'html' => $html]);
    }

and my /views/wall/post.blade.php :

<div class="ui post">
<div class="name">User : {{ $post->user_name }}</div>
<div class="content">{{ $post->content }}</div>
</div>

Below is my question:

how do i get the content from post.blade.php with user_name and content return as below to $html in new() when i post name=kenny and content=testing:

<div class="ui post">
<div class="name">User : Kenny</div>
<div class="content">Testing</div>
</div>

and i just use jquery to prepend above code to my page?

Thanks

{Sorry if i got bad grammar in my english}

Select an arrray from JSON data on PHP

everyone!

I'm working on a movie website(which obviously not completed). I want to know how to export data from an API and select an array from JSON data on PHP. In this case, I want to output the title of the movie but it seems to not working. I get this error: Notice: Trying to get property of non-object. From the error, I know that I'm trying to output an object, not a string but I don't know how to resolve it.

Here's my index.php file:

<?php
require_once('includes/variables.php');
 ?>
 <!DOCTYPE html>
 <html>
    <body>
    <?php
        echo $movieNameList->data->movies[1]->id;
    ?>
</body>
</html>

includes/variables.php file:

 <?php
 $getMovieList = file_get_contents('http://ift.tt/1xsOjG3');
 $movieNameList = json_decode($getMovieList[0]);
 ?>

http://ift.tt/1xsOjG3 file if you're lazy:

{  
   "status":"ok",
   "status_message":"Query was successful",
   "data":{  
      "movie_count":4220,
      "limit":2,
      "page_number":1,
      "movies":[  
         {  
            "id":4247,
            "url":"https:\/\/yts.to\/movie\/rem-by-mtv-2014",
            "imdb_code":"tt4066748",
            "title":"R.E.M. by MTV",
            "title_long":"R.E.M. by MTV (2014)",
            "slug":"rem-by-mtv-2014",
            "year":2014,
            "rating":8,
            "runtime":107,
            "genres":[  
               "Documentary"
            ],
            "language":"English",
            "mpa_rating":"Unknown",
            "background_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/rem_by_mtv_2014\/background.jpg",
            "small_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/rem_by_mtv_2014\/small-cover.jpg",
            "medium_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/rem_by_mtv_2014\/medium-cover.jpg",
            "state":"ok",
            "torrents":[  
               {  
                  "url":"https:\/\/yts.to\/torrent\/download\/1F28D13F40AE91AECC58D649F5F9D84D29321632.torrent",
                  "hash":"1F28D13F40AE91AECC58D649F5F9D84D29321632",
                  "quality":"720p",
                  "seeds":1063,
                  "peers":544,
                  "size":"812.23 MB",
                  "size_bytes":851680192,
                  "date_uploaded":"2015-06-28 08:49:09",
                  "date_uploaded_unix":1435438149
               },
               {  
                  "url":"https:\/\/yts.to\/torrent\/download\/DED26397FD36DFC932BB5EEEC82D25204699943C.torrent",
                  "hash":"DED26397FD36DFC932BB5EEEC82D25204699943C",
                  "quality":"1080p",
                  "seeds":247,
                  "peers":419,
                  "size":"1.65 GB",
                  "size_bytes":1766838835,
                  "date_uploaded":"2015-06-28 22:55:41",
                  "date_uploaded_unix":1435488941
               }
            ],
            "date_uploaded":"2015-06-28 08:49:06",
            "date_uploaded_unix":1435438146
         },
         {  
            "id":4245,
            "url":"https:\/\/yts.to\/movie\/bigfoot-county-2012",
            "imdb_code":"tt2108605",
            "title":"Bigfoot County",
            "title_long":"Bigfoot County (2012)",
            "slug":"bigfoot-county-2012",
            "year":2012,
            "rating":2.9,
            "runtime":82,
            "genres":[  
               "Horror",
               "Mystery"
            ],
            "language":"English",
            "mpa_rating":"R",
            "background_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/bigfoot_county_2012\/background.jpg",
            "small_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/bigfoot_county_2012\/small-cover.jpg",
            "medium_cover_image":"https:\/\/s.ynet.io\/assets\/images\/movies\/bigfoot_county_2012\/medium-cover.jpg",
            "state":"ok",
            "torrents":[  
               {  
                  "url":"https:\/\/yts.to\/torrent\/download\/25E5FBDAD49BFD067EEB7778EF1CED753E0E608C.torrent",
                  "hash":"25E5FBDAD49BFD067EEB7778EF1CED753E0E608C",
                  "quality":"720p",
                  "seeds":324,
                  "peers":183,
                  "size":"693.01 MB",
                  "size_bytes":726671831,
                  "date_uploaded":"2015-06-27 14:02:07",
                  "date_uploaded_unix":1435370527
               }
            ],
            "date_uploaded":"2015-06-27 14:02:06",
            "date_uploaded_unix":1435370526
         }
      ]
   },
   "@meta":{  
      "server_time":1435498431,
      "server_timezone":"Pacific\/Auckland",
      "api_version":2,
      "execution_time":"12.3 ms"
   }
}

Can not get one item out of Json

tryign to pull the items from this json, it dosent work, any suggestions?

   <pre>{{statistics|json}}</pre>

<div class = "list">
        <a class =" item" 
           ng-repeat="item in statistics ">




         <p class="title"> {{item.token}} </p>  


        </a>
</div>

how to parse json using GSON in android?

can any body parse this json for me using GSON i tried many time but, failed.

{
    "posting_detail": {
        "posting_id": "14",
        "posting_title": "LuLu Last Offer",
        "posting_desc": "dqwewqewe",
        "mobile_number": "2344234234",
        "phone_number": "34234324",
        "address": "fefdsfds",
        "city_name": "Abu Dhabi",
        "created_on": "2015-06-22 14:55:05",
        "normal_price": null,
        "images": [
            {
                "photo_img": "http://xyz/images/posting/IMG_1212121219.jpg"
            },
            {
                "photo_img": "http://xyz/images/posting/IMG_1212121220.jpg"
            }
        ]
    }
}

Thanks in advance

Passing parameter to partial view - Rails 4/postgresql/json

I have a Deal model with a column/attribute called 'deal_info' which is a json column.

It looks like this for example

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

On my view deal.html.erb, i have:

<%= for deal_nb in 0..@deal.number_of_deals do %>
  <div class="modal fade" id="myInfoModal<%= modal_nb %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <!-- render the right modal type -->
    <%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: deal_nb  %>
  </div>
<% end %>

Above, as you see above, I'd like to pass for each iteration of the loop inside parameter_i_want_to_pass the number of the iteration loop (2nd iteration would be parameter_i_want_to_pass= 2 for example).

On the partial I have:

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="myModalLabel">this is mt4</h4>
    </div>
    <div class="modal-body">
      this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]['text1'] %> 

    </div>
  </div>

I get the following error:

no implicit conversion of String into Integer (on line "this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]")

Actually I even tried to detect more easily the bug by just passing a set number instead of the variable 'deal_nb'

<%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: 2  %>

But I still get exactly the same error.

Best way to display JSON (well formatted) in UITextView or UIWebView in iOS

I need to display SJON in my iPhone app. Currently I am getting unformatted JSON - like one big string with no indentation.

What would be the best way to display this?

Thanks,

Safe Dynamic JSON Casts In Swift

I suspect that I am not quite grokking Swift 1.2, and I need to RTFM a bit more.

I'm working on a Swift app that reads JSON data from a URI.

If the JSON data is bad, or nonexistent, no issue. The JSON object never instantiates.

However, if the JSON data is good JSON, but not what I want, the object instantiates, but contains a structure that is not what I'm looking for, I get a runtime error.

I looked at using Swift's "RTTI" (dynamicType), but that always returns "<Swift.AnyObject>", no matter what the data is.

I want the JSON to be a specific format: An array of Dictionaries:

[[String:String]]! JSON: [{"key":"value"},{"key","value"},{"Key":"value"}]

If I feed it a single element:

{"Key":"value"}

The routine I have tries to cast it, and that fails.

I want to test the JSON object to make sure that it has a structure I want before casting.

    if(nil != inData) {
        let rawJSONObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(inData, options: nil, error: nil)
        println("Type:\(rawJSONObject.dynamicType)")
        if(nil != rawJSONObject) {
            // THE LINE BELOW BLOWS UP IF I FEED IT "BAD/GOOD" JSON:
            let jsonObject: [[String:String]]! = rawJSONObject as! [[String:String]]!
            // I NEED TO TEST IT BEFORE DOING THE CAST
            if((nil != jsonObject) && (0 < jsonObject.count)) {
                let jsonDictionary: [String:String] = jsonObject[0]
                if("1" == jsonDictionary["semanticAdmin"]) { // We have to have the semantic admin flag set.
                    let testString: String!  = jsonDictionary["versionInt"]

                    if(nil != testString) {
                        let version = testString.toInt()

                        if(version >= self.s_minServerVersion) {    // Has to be a valid version for us to pay attention.
                            self.serverVersionAsInt = version!
                        }
                    }
                }
            }
        }
    }

My question is, is there a good way to test an NSJSONSerialization response for the structure of the JSON before uwinding/casting it?

I feel as if this question may be closer to what I need, but I am having trouble "casting" it to my current issue.

JSON Parsing in Ruby

I'm trying to parse the below from JSON (using the JSON gem) in Ruby:

"daily":{"summary":"Light rain today through Saturday, with temperatures rising to 88°F on Saturday.","icon":"rain","data":[{"time":1435464000,"precipProbability":0.99}]}

Currently what I have is this: forecast["daily"]["data"], but I want to get the precipProbability for time "1435464000". Any suggestion on how to complete my current JSON parsing "query"?

How do I write a json file in a specific format?

I'm nearly done with my program, it loads perfect but one issue I'm having is when I edit the json file through my program, I cannot reload the json file because when I save the file, the formatting becomes different.

So my question is how do I format the json file the same as I'm reading it?

Here's my method for writting a new json file.

    public static boolean write(File npcDefFile) {
    try {
        FileWriter writer = new FileWriter(npcDefFile);
        Throwable localThrowable3 = null;
        try {
            Gson gson = new Gson();
            String json = gson.toJson(NPCDefinitions.getNPCDefinitions());
            writer.write(json);
            writer.flush();
        } catch (Throwable localThrowable1) {
            localThrowable3 = localThrowable1;
            throw localThrowable1;
        } finally {
            if (writer != null) {
                if (localThrowable3 != null) {
                    try {
                        writer.close();
                    } catch (Throwable localThrowable2) {
                        localThrowable3.addSuppressed(localThrowable2);
                    }
                } else {
                    writer.close();
                }
            }
        }
    } catch (NullPointerException | IOException e) {
        System.out.println(e.getLocalizedMessage());
        return false;
    }
    return true;
}

Here's the correct format (3 Space Tab)

    [
  {
    "id": 0,
    "name": "Hans",
    "examine": "Servant of the Duke of Lumbridge.",
    "combat": 0,
    "size": 1,
    "attackable": false,
    "aggressive": false,
    "retreats": false,
    "poisonous": false,
    "respawn": 10,
    "maxHit": 0,
    "hitpoints": 0,
    "attackSpeed": 7,
    "attackAnim": 0,
    "defenceAnim": 0,
    "deathAnim": 0,
    "attackBonus": 0,
    "defenceMelee": 0,
    "defenceRange": 0,
    "defenceMage": 0
  },
  {
    "id": 1,
    "name": "Man",
    "examine": "One of Wildy's many citizens.",
    "combat": 2,
    "size": 1,
    "attackable": true,
    "aggressive": false,
    "retreats": true,
    "poisonous": false,
    "respawn": 10,
    "maxHit": 1,
    "hitpoints": 7,
    "attackSpeed": 7,
    "attackAnim": 422,
    "defenceAnim": 1834,
    "deathAnim": 836,
    "attackBonus": 9,
    "defenceMelee": 9,
    "defenceRange": 9,
    "defenceMage": 0
  }
]

Here's the format after I save the file to a new json file. (Compact)

[{"id":0,"name":"Hans","examine":"Servant of the Duke of               Lumbridge.","combat":0,"size":1,"attackable":false,"aggressive":false,"retreats":false,"poisonous":false,"respawn":10,"maxhit":0,"hp":0,"attackspeed":7,"attackanim":0,"defenceanim":0,"deathanim":0,"attackbonus":0,"defencemelee":0,"defencerange":0,"defencemage":0},{"id":1,"name":"Man","examine":"One of Wildy\u0027s many citizens.","combat":2,"size":1,"attackable":true,"aggressive":false,"retreats":true,"poisonous":false,"respawn":10,"maxhit":1,"hp":7,"attackspeed":7,"attackanim":422,"defenceanim":1834,"deathanim":836,"attackbonus":9,"defencemelee":9,"defencerange":9,"defencemage":0}]

This is how I'm loading the json file.

    /**
 * A dynamic method that allows the user to read and modify the parsed data.
 *
 * @param reader
 *            the reader for retrieving the parsed data.
 * @param builder
 *            the builder for retrieving the parsed data.
 */
public abstract void load(JsonObject reader, Gson builder);

/**
 * Loads the parsed data. How the data is loaded is defined by
 * {@link JsonLoader#load(JsonObject, Gson)}.
 *
 * @return the loader instance, for chaining.
 */
public final JsonLoader load() {
    try (FileReader in = new FileReader(Paths.get(path).toFile())) {
        JsonParser parser = new JsonParser();
        JsonArray array = (JsonArray) parser.parse(in);
        Gson builder = new GsonBuilder().create();

        for (int i = 0; i < array.size(); i++) {
            JsonObject reader = (JsonObject) array.get(i);
            load(reader, builder);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return this;
}

Any help would be appreciated.

EDIT:

Here's an exception that was caught.

java.lang.NullPointerException
at NpcDefinitionLoader.load(NpcDefinitionLoader.java:28)
at JsonLoader.load(JsonLoader.java:56)
at NPCDefinitions.loadNPCDefinitions(NPCDefinitions.java:76)
at DefinitionEditor.loadFile(DefinitionEditor.java:171)
at DefinitionEditor.loadButtonActionPerformed(DefinitionEditor.java:790)
at DefinitionEditor.actionPerformed(DefinitionEditor.java:827)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased

Here's the first line the error occured.

int maxHit = reader.get("maxHit").getAsInt();

Second line error

load(reader, builder);

How to i parse this json? [duplicate]

This question already has an answer here:

    String jsondata="{\"studentResult\":[{\"sem1\" :[{\"subname\":\"TOC\",\"subcode\":\"1009\",\"subcredit\":\"6\",\"subgrade\":\"AB\"},
    {\"subname\":\"DS\",\"subcode\":\"10090\",\"subcredit\":\"5\",\"subgrade\":\"BB\"},
    {\"subname\":\"TOC\",\"subcode\":\"1009\",\"subcredit\":\"6\",\"subgrade\":\"AB\"}]},{\"sem2\":
   [{\"subname\":\"AAS\",\"subcode\":\"111009\",\"subcredit\":\"6\",\"subgrade\":\"AB\"},
{\"subname\":\"AE\",\"subcode\":\"103309\",\"subcredit\":\"6\",\"subgrade\":\"DD\"}] }]}";