2016-03-13 18 views
0

我在我的Spark流應用程序中有一個RDD [twitter4j.Status](來自Spark API中的TwitterUtils),我想將其轉換爲此json,其中Id將是(status => status.getId()。toString)和Text將是(status => status.getText())將RDD [狀態]轉換爲特定的json的最有效方法

我嘗試了幾件事,但我對結果不滿意,並想知道是否有是一個非常有效的方法來做到這一點。

{ 
    "Inputs": [{ 
     "Id": "1", 
     "Text": "hello world" 
    }, 
    { 
     "Id": "2", 
     "Text": "hello foo world" 
    }, 
    { 
     "Id": "three", 
     "Text": "hello my world" 
    }] 
} 
+0

「Efficient」在這裏是不明確的。你想爲人類或電腦節省時間嗎? –

+0

:)對於計算機 –

+0

「有幾件事,但我對結果不滿意」嗯,既然你不會告訴我們你已經試過了什麼,我們不知道該怎麼提出可能會讓你開心的事, –

回答

0

在端我創建2 java類輸入和InputsValue和槓桿com.google.code.gson:GSON:2.6.2至對象轉換爲JSON字符串。 爲什麼Java類而不是Scala的?因爲gson支持List,其中T是一個自定義對象,所以使用Java類非常容易,例如與spray-io相比。我可能是錯的,但這是我迄今發現的。

public class Input { 

    public Input(String id, String text) { 
     this.Id = id; 
     this.Text = text; 
    } 

    public String Id; 
    public String Text; 
} 

public class InputsValue { 

    public InputsValue(List<Input> inputs) { 
     this.Inputs = inputs; 
    } 

    public List<Input> Inputs; 
} 

val i1 = rdd.map(o => new Input(o.getId().toString, o.getText())).collect().toList; 
val iv1: InputsValue = new InputsValue(i1) 
val inputs = gson.toJson(iv1) 
相關問題