Java org.json.JSONObject的C#等价物



我正在尝试将一个java项目转换为C#。在下面的文章中,我不知道如何转换Json部分。

Cursor resultSet = helper.openDataBase().rawQuery("Select * from word where wname=?", new String[] {String.valueOf(editable)});
TextView TextView_FA =  findViewById(R.id.textView_FA);

if( resultSet.moveToFirst())
{
String str_json = resultSet.getString(2);
try {
JSONObject obj = new JSONObject(str_json);
String trans = obj.getJSONArray("ss").optJSONObject(0) .getString("s");
TextView_FA.setText(trans);
} catch (JSONException e) {
TextView_FA.setText(e.getLocalizedMessage());
}

}
else {
TextView_FA.setText("no translation found");
}

这就是我尝试过的:

EditText EditText_en = FindViewById<EditText>(Resource.Id.EditText_en);
Java.IO.File fil = new Java.IO.File(db_src);

SQLiteDatabase db = SQLiteDatabase.OpenDatabase(fil,null);
Android.Database.ICursor resultSet = db.RawQuery("Select * from word where wname =? ",new[]{ EditText_en.Text});


TextView TextView_FA = FindViewById<TextView>(Resource.Id.TextView_fa);
if (resultSet.MoveToFirst())
{
String str_json = resultSet.GetString(2);

try
{

// JSONObject obj = new JSONObject(str_json);
// String trans = obj.getJSONArray("ss").optJSONObject(0).getString("s");
TextView_FA.Text = trans;
}
catch (Exception e)
{
TextView_FA.Text = e.Message;
}

}
else
{
TextView_FA.Text = "no translation found" ;
}

我评论的两句话就是问题所在。正如一些互联网文档所说,我试图使用System.Text.Json或System.Json,但VS2019intellisense无法将它们识别为有效的库。

使用NewtonSoft.JSon可能是反序列化JSon最常见的方法,而且比System.Text.JSon更容易(宽容(。如果您有已知的类型,使用JSon也更容易。我不知道你的JSon字符串是什么样子的,但我已经制作了我自己的示例字符串

//[
// {
//  color: "red",
//  value: "#f00"
// },
// {
//  color: "green",
//  value: "#0f0"
// },
// {
//  color: "blue",
//  value: "#00f"
// }
//]
string myJson = "[rnt{rntt"color": "red",rntt"value": "#f00"rnt},rnt{rntt"color": "green",rntt"value": "#0f0"rnt},rnt{rntt"color": "blue",rntt"value": "#00f"rnt}rntrn]";

如果您有一个类或可以定义它,那么使用JSon会更容易,但我已经创建了一个没有使用类的示例

public class custColor
{
public string color { get; set; }
public string value { get; set; }
}

NewtonSoft和System.Text.Json 的示例

//NewtonSoft JSON
var arrayOfColors = JsonConvert.DeserializeObject<custColor[]>(myJson);
var valueFromArray = arrayOfColors[0].value;    //Will give #f00
var dynamicColorArray = JsonConvert.DeserializeObject<dynamic>(myJson);
var valueFromDynArray = dynamicColorArray[0].value; //Will also give #f00
//System.Text.Json
var stjArrayOfColors = System.Text.Json.JsonSerializer.Deserialize<custColor[]>(myJson);
var stjValueFromArray = stjArrayOfColors[0].value;    //Will give #f00

最新更新