解析JSON字符串以获取一些参考数据

时间:2018-09-22 08:35:28

标签: c# json

如何在C#中解析给定的字符串? 我要提取以下值-用户名和ref_id

data Value m = Wrong
             | Num Int
             | Fun (Value m -> m (Value m))

3 个答案:

答案 0 :(得分:2)

以下是使用Newtonsoft.JSON解析JSON的四种不同方法,这是最常用的JSON解析C#库之一。

示例1

反序列化为我们自己的类结构:

用法:

Root output = JsonConvert.DeserializeObject<Root>(json);
var refId = output.SomeUser.ReferenceId;

类结构:

/// <summary>
/// Class representing the JSON
/// </summary>
public class Root
{
    [JsonProperty("User")]
    public User SomeUser { get; set; }

    public class User
    {
        [JsonProperty("username")]
        public string UserName { get; set; }
        [JsonProperty("email")]
        public string EMail { get; set; }
        [JsonProperty("ref_id")]
        public string ReferenceId { get; set; }
        // etc.
    }
}

示例2

使用动态类型:

dynamic rootObject = JObject.Parse(json);
dynamic user = rootObject.User;
var refId = user.ref_id;
var username = user.username;

示例3

令牌/字符串属性名称和提取值的泛型:

JObject root = JObject.Parse(json);
var refId = root["User"]["ref_id"].Value<string>();
var username = root["User"]["username"].Value<string>();

示例4

使用选择令牌:

var rootObject = JObject.Parse(json);
var refId = rootObject.SelectToken("User.ref_id");
var username = rootObject.SelectToken("User.username");

答案 1 :(得分:0)

您可以使用System.Web.Script.Serialization.JavaScriptSerializer将字符串解析为JSON dynamic对象

这里是一个例子,

lambda_pathlet=0.001
pathlets_learned=30
trajectory_amount=65

def saveLambdaAndFrequency(lambdaPathlet, pathlets_learned,trajectory_amount):
    columns = ["lambda", "pathlets_learned", "trajectory_amount"]
    df_lambda_pathlets=pd.DataFrame(columns)
    df_lambda_pathlets = df_lambda_pathlets.set_value(lambdaPathlet, pathlets_learned,trajectory_amount)
    res= "\"lambda\" \"pathlets_learned\" \"trajectory_amount\""
    lambda_auswertung = 'Lambda_Pathlet_Auswertung.txt'
    f = open(lambda_auswertung, 'w+')
    with open(lambda_auswertung, 'w+') as f:
        np.savetxt(f,df_lambda_pathlets.values,comments='',fmt='%d',header=res)
    f.close()

您还可以检查Newtonsoft.JSON

答案 2 :(得分:0)

或者,您可以看看这种“快速而肮脏”的方法。

两种简单的方法:

static string QuickAndDirtyJsonLookupText(string json, string key) =>
    QuickAndDirtyJsonFind(json, key).Split('"')[1];
static string QuickAndDirtyJsonFind(string json, string key) {
    int keyIndex = json.IndexOf($"\"{key}\":");
    if (keyIndex < 0)
        throw new KeyNotFoundException($"Key \"{key}\" not found in '{json}'.");
    return json.Substring(keyIndex + 3 + key.Length).TrimStart();
}

让您查找所需的内容,例如:

const string json =
    "{"+
    "  \"User\":{" +
    "     \"username\":\"Vinayaka\"," +
    "     \"email\":\"Vinayaka@mindsol.in\"," +
    "     \"ref_id\":\"43523543\"," +
    "     \"state_code\":\"UP\"," +
    "     \"active_status\":\"1\"," +
    "     \"user_type\":\"Admin\"," +
    "     \"last_active\":\"2018-09-22 13:50:23\"" +
    "  }" +
    "}";
Assert.AreEqual("Vinayaka", QuickAndDirtyJsonLookupText(json, "username"));
Assert.AreEqual("43523543", QuickAndDirtyJsonLookupText(json, "ref_id"));

当然,这确实是“快速而又肮脏的”,并且只有在您提前知道json的结构并且知道文本值不包含引号的情况下才有效(通常是这种情况)。例如,您还可以轻松添加自己的QuickAndDirtyJsonLookupInt

如果您希望采用结构更完整的方法并提供完整的源代码,请在https://github.com/Dbquity/Json上查看我的轻量级解析器和生成器。