2011-06-28 16 views
46

मैं जावा का उपयोग कर रहा एक यूआरएल है कि एक JSON ऑब्जेक्ट कॉल करने के लिए पार्स करने के लिए?कैसे एक JSON इनपुट धारा

+0

स्टैक ओवरफ़्लो में आपका स्वागत है! कृपया प्रश्न पोस्ट करते समय अपने कोड को सही ढंग से प्रारूपित करना याद रखें। –

उत्तर

6

उपयोग जैक्सन नक्शा करने के लिए json इनपुट धारा बदल सकते हैं या आपत्ति http://jackson.codehaus.org/

वहाँ भी json के लिए कुछ अन्य उपयोगी पुस्तकालय हैं, तो आप गूगल कर सकते हैं: json जावा

+8

कृपया प्रत्येक उत्तरदायी – Jayen

+0

के लिए उदाहरण के साथ इस उत्तर में सुधार करें जैक्सन https://github.com/FasterXML/jackson – disrvptor

+0

के लिए अद्यतन लिंक यह अनिवार्य रूप से कुछ भी नहीं बताता है। –

4

एक पुस्तकालय का प्रयोग करें।

  • GSON
  • Jackson
  • या कई अन्य JSON पुस्तकालयों कि वहाँ बाहर हैं।
-3
{ 
    InputStream is = HTTPClient.get(url); 
    InputStreamReader reader = new InputStreamReader(is); 
    JSONTokener tokenizer = new JSONTokener(reader); 
    JSONObject jsonObject = new JSONObject(tokenizer); 
} 
+3

क्या JSONTokener को JSON स्ट्रिंग की आवश्यकता नहीं है, इनपुट इनपुट नहीं है? – VMcPherron

+4

[लिंक] (http://developer.android.com/reference/org/json/JSONTokener.html) इंगित करता है कि एंड्रॉइड के लिए, JSONTokener केवल एक स्ट्रिंग लेता है। – VMcPherron

76

मेरा सुझाव है कि आप एक रीडर का उपयोग करने के अपने InputStream कन्वर्ट करना होगा

BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); 
StringBuilder responseStrBuilder = new StringBuilder(); 

String inputStr; 
while ((inputStr = streamReader.readLine()) != null) 
    responseStrBuilder.append(inputStr); 
new JSONObject(responseStrBuilder.toString()); 

मैं in.toString (कोशिश की) लेकिन यह रिटर्न:।

getClass().getName() + '@' + Integer.toHexString(hashCode()) 

(प्रलेखन की तरह यह कहता है कि यह ऑब्जेक्ट से स्ट्रिंग को प्राप्त करता है)

+1

यदि प्रदर्शन एक मुद्दा है कि स्ट्रिंगबिल्डर की डिफ़ॉल्ट क्षमता 16 वर्ण है, तो आप अपनी औसत टेक्स्ट लंबाई से अधिक लंबाई का उपयोग कर इसे बढ़ा सकते हैं, उदाहरण के लिए 'नया स्ट्रिंगबिल्डर (2048) '। रेखा से लाइन पढ़ना शायद प्रदर्शन के लिए सबसे अच्छा नहीं है। –

+0

यू ने मेरी जान बचाई, lol tnx – vinidog

5

उन था के लिए टी तथ्य यह है कि आप इस तरह InputStream के toString विधि का उपयोग नहीं कर सकते ने बताया https://stackoverflow.com/a/5445161/1304830 देखें:

मेरे सही जवाब तो होगा:

import org.json.JSONObject; 

public static String convertStreamToString(java.io.InputStream is) { 
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); 
    return s.hasNext() ? s.next() : ""; 
} 

... 

JSONObject json = new JSONObject(convertStreamToString(url.openStream()); 
+2

स्ट्रीम को स्ट्रिंग में कनवर्ट करने के लिए आपको पूरी सामग्री को स्मृति में रखना होगा, जहां एक स्ट्रीम नहीं होगी। –

+1

भले ही यह मेमोरी भारी हो, फिर भी यह विधि कुछ बिंदुओं की योग्यता प्राप्त करती है क्योंकि छोटे JSON ऑब्जेक्ट्स के लिए यह बहुत स्पष्ट और कॉम्पैक्ट है –

21

सभी मौजूदा जवाब मानते हैं कि यह खींचने के लिए ठीक है संपूर्ण JSON स्मृति में जहां इनपुटस्ट्रीम का लाभ यह है कि आप थोड़ा कम इनपुट पढ़ सकते हैं। यदि आप एक बार में पूरी जेसन फ़ाइल को पढ़ने से बचना चाहते हैं तो मैं जैक्सन लाइब्रेरी का उपयोग करने का सुझाव दूंगा (जो मेरा निजी पसंदीदा है लेकिन मुझे यकीन है कि जीसन जैसे अन्य समान कार्य हैं)।

जैक्सन के साथ आप एक समय में एक सेक्शन पढ़ने के लिए एक जेसन पार्सर का उपयोग कर सकते हैं। नीचे कोड का एक उदाहरण मैंने लिखा है जो एक इटरेटर में जेसनऑब्जेक्ट्स के एक ऐरे के पढ़ने को लपेटता है। यदि आप सिर्फ जैक्सन का एक उदाहरण देखना चाहते हैं, तो initJsonParser, initFirstElement, और initNextObject विधियों को देखें।

public class JsonObjectIterator implements Iterator<Map<String, Object>>, Closeable { 
    private static final Logger LOG = LoggerFactory.getLogger(JsonObjectIterator.class); 

    private final InputStream inputStream; 
    private JsonParser jsonParser; 
    private boolean isInitialized; 

    private Map<String, Object> nextObject; 

    public JsonObjectIterator(final InputStream inputStream) { 
     this.inputStream = inputStream; 
     this.isInitialized = false; 
     this.nextObject = null; 
    } 

    private void init() { 
     this.initJsonParser(); 
     this.initFirstElement(); 
     this.isInitialized = true; 
    } 

    private void initJsonParser() { 
     final ObjectMapper objectMapper = new ObjectMapper(); 
     final JsonFactory jsonFactory = objectMapper.getFactory(); 

     try { 
      this.jsonParser = jsonFactory.createParser(inputStream); 
     } catch (final IOException e) { 
      LOG.error("There was a problem setting up the JsonParser: " + e.getMessage(), e); 
      throw new RuntimeException("There was a problem setting up the JsonParser: " + e.getMessage(), e); 
     } 
    } 

    private void initFirstElement() { 
     try { 
      // Check that the first element is the start of an array 
      final JsonToken arrayStartToken = this.jsonParser.nextToken(); 
      if (arrayStartToken != JsonToken.START_ARRAY) { 
       throw new IllegalStateException("The first element of the Json structure was expected to be a start array token, but it was: " + arrayStartToken); 
      } 

      // Initialize the first object 
      this.initNextObject(); 
     } catch (final Exception e) { 
      LOG.error("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e); 
      throw new RuntimeException("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e); 
     } 

    } 

    private void initNextObject() { 
     try { 
      final JsonToken nextToken = this.jsonParser.nextToken(); 

      // Check for the end of the array which will mean we're done 
      if (nextToken == JsonToken.END_ARRAY) { 
       this.nextObject = null; 
       return; 
      } 

      // Make sure the next token is the start of an object 
      if (nextToken != JsonToken.START_OBJECT) { 
       throw new IllegalStateException("The next token of Json structure was expected to be a start object token, but it was: " + nextToken); 
      } 

      // Get the next product and make sure it's not null 
      this.nextObject = this.jsonParser.readValueAs(new TypeReference<Map<String, Object>>() { }); 
      if (this.nextObject == null) { 
       throw new IllegalStateException("The next parsed object of the Json structure was null"); 
      } 
     } catch (final Exception e) { 
      LOG.error("There was a problem initializing the next Object: " + e.getMessage(), e); 
      throw new RuntimeException("There was a problem initializing the next Object: " + e.getMessage(), e); 
     } 
    } 

    @Override 
    public boolean hasNext() { 
     if (!this.isInitialized) { 
      this.init(); 
     } 

     return this.nextObject != null; 
    } 

    @Override 
    public Map<String, Object> next() { 
     // This method will return the current object and initialize the next object so hasNext will always have knowledge of the current state 

     // Makes sure we're initialized first 
     if (!this.isInitialized) { 
      this.init(); 
     } 

     // Store the current next object for return 
     final Map<String, Object> currentNextObject = this.nextObject; 

     // Initialize the next object 
     this.initNextObject(); 

     return currentNextObject; 
    } 

    @Override 
    public void close() throws IOException { 
     IOUtils.closeQuietly(this.jsonParser); 
     IOUtils.closeQuietly(this.inputStream); 
    } 

} 

आप स्मृति के उपयोग के बारे में परवाह नहीं करते हैं, तो यह निश्चित रूप से आसान पूरी फ़ाइल पढ़ सकते हैं और के रूप में एक बड़ा Json उसे पार्स के रूप में अन्य उत्तर में उल्लेख करने के लिए किया जाएगा।

2

आप Jackson Databind उपयोग करने के लिए (Spring अपने HttpMessageConverters लिए डिफ़ॉल्ट रूप से उपयोग करता है) की तरह है, तो आप ObjectMapper.readTree(InputStream) एपीआई का उपयोग कर सकते हैं। उदाहरण के लिए,

ObjectMapper mapper = new ObjectMapper(); 
JsonNode json = mapper.readTree(myInputStream); 
संबंधित मुद्दे